JavaScript: how to filter deep JSON objects

I have an array of deep JSON objects that look like this:

var hierarchy = [
  {
    "title": "category 1",
    "children": [
      {"title": "subcategory 1",
        "children": [
          {"id": 1, "title": "name 1"},
          {"id": 2, "title": "name 2"},
          {"id": 3, "title": "name 3"}
        ]
      },
      {"title": "subcategory 2",
        "children": [
          {"id": 1, "title": "name 4"}
        ]
      }
    ]
  },
  {
    "title": "category 2",
    "children": [etc. - shortened for brevity]
  }
];

So basically this is a hierarchy - there are categories that may have subcategories that contain objects with some identifiers and names. I also have an array of identifiers that are associated with the deepest level of the hierarchy (objects without children), and I need to filter out this set of objects so that only (auxiliary) categories containing certain objects remain.

So, for example, if I had an array containing two identifiers:

var IDs = [2, 3];

the result will be:

var hierarchy = [
  {
    "title": "category 1",
    "children": [
      {"title": "subcategory 1",
        "children": [
          {"id": 2, "title": "name 2"},
          {"id": 3, "title": "name 3"}
        ]
      }
    ]
  }
];

i.e. the whole, the entire object of category 2 is deleted, the entire "subcategory 2" is deleted, the object with the identifier "1" is deleted.

, - , , .., , , .

.

+4
3

, , node. node node, , , , .

, , . - , .

:

var currentPath = [];

function depthFirstTraversal(o, fn) {
    currentPath.push(o);
    if(o.children) {
        for(var i = 0, len = o.children.length; i < len; i++) {
            depthFirstTraversal(o.children[i], fn);
        }
    }
    fn.call(null, o, currentPath);
    currentPath.pop();
}

function shallowCopy(o) {
    var result = {};
    for(var k in o) {
        if(o.hasOwnProperty(k)) {
            result[k] = o[k];
        }
    }
    return result;
}

function copyNode(node) {
    var n = shallowCopy(node);
    if(n.children) { n.children = []; }
    return n;
}

function filterTree(root, ids) {
    root.copied = copyNode(root); // create a copy of root
    var filteredResult = root.copied;

    depthFirstTraversal(root, function(node, branch) {
        // if this is a leaf node _and_ we are looking for its ID
        if( !node.children && ids.indexOf(node.id) !== -1 ) {
            // use the path that the depthFirstTraversal hands us that
            // leads to this leaf.  copy any part of this branch that
            // hasn't been copied, at minimum that will be this leaf
            for(var i = 0, len = branch.length; i < len; i++) {
                if(branch[i].copied) { continue; } // already copied

                branch[i].copied = copyNode(branch[i]);
                // now attach the copy to the new 'parellel' tree we are building
                branch[i-1].copied.children.push(branch[i].copied);
            }
        }
    });

    depthFirstTraversal(root, function(node, branch) {
        delete node.copied; // cleanup the mutation of the original tree
    });

    return filteredResult;
}

function filterTreeList(list, ids) {
    var filteredList = [];
    for(var i = 0, len = list.length; i < len; i++) {
        filteredList.push( filterTree(list[i], ids) );
    }
    return filteredList;
}

var hierarchy = [ /* your data here */ ];
var ids = [1,3];

var filtered = filterTreeList(hierarchy, ids);
+5

, 2 . , .., . pure-javascript jQuery. javascript , jQuery, " " , , .

function jsFilter(idList){
  var rsltHierarchy=[];
  for (var i=0;i<hierarchy.length;i++) {
    var currCatg=hierarchy[i];
    var filtCatg={"title":currCatg.title, "children":[]};
    for (var j=0;j<currCatg.children.length;j++) {
  	var currSub=currCatg.children[j];
  	var filtSub={"title":currSub.title, "children":[]}
  	for(var k=0; k<currSub.children.length;k++){
  		if(idList.indexOf(currSub.children[k].id)!==-1)
  		   filtSub.children.push({"id":currSub.children[k].id, "title":currSub.children[k].title});
  	}
  	if(filtSub.children.length>0)
  		filtCatg.children.push(filtSub);
    }
    if(filtCatg.children.length>0)
  	rsltHierarchy.push(filtCatg);
  }
  return rsltHierarchy;
}

function jqFilter(idList){
  var rsltHierarchy=[];
  $.each(hierarchy, function(index,currCatg){
      var filtCatg=$.extend(true, {}, currCatg);
      filtCatg.children=[];
  	$.each(currCatg.children, function(index,currSub){
        var filtSub=$.extend(true, {}, currSub);
  	  filtSub.children=[];
  	  $.each(currSub.children, function(index,currSubChild){
  		if(idList.indexOf(currSubChild.id)!==-1)
  		  filtSub.children.push($.extend(true, {}, currSubChild));
        });
  	  if(filtSub.children.length>0)
  		filtCatg.children.push(filtSub);
      });
      if(filtCatg.children.length>0)
  	  rsltHierarchy.push(filtCatg);
  });
  return rsltHierarchy;
}

//Now test the functions...
var hierarchy = eval("("+document.getElementById("inp").value+")");
var IDs = eval("("+document.getElementById("txtBoxIds").value+")");

document.getElementById("oupJS").value=JSON.stringify(jsFilter(IDs));
$(function() {
   $("#oupJQ").text(JSON.stringify(jqFilter(IDs)));
});
#inp,#oupJS,#oupJQ {width:400px;height:100px;display:block;clear:all}
#inp{height:200px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

ID List: <Input id="txtBoxIds" type="text" value="[2, 3]">

<p>Input:
<textarea id="inp">[
  {
    "title": "category 1",
    "children": [
      {"title": "subcategory 11",
        "children": [
          {"id": 1, "title": "name 1"},
          {"id": 2, "title": "name 2"},
          {"id": 3, "title": "name 3"}
        ]
      },
      {"title": "subcategory 12",
        "children": [
          {"id": 1, "title": "name 4"}
        ]
      }
    ]
  },
  {
    "title": "category 2",
    "children": [
      {"title": "subcategory 21",
        "children": [
          {"id": 3, "title": "name cat2sub1id3"},
          {"id": 5, "title": "name cat2sub1id5"}
        ]
      },
      {"title": "subcategory 22",
        "children": [
          {"id": 6, "title": "name cat2sub2id6"},
          {"id": 7, "title": "name cat2sub2id7"}
        ]
      }
    ]
  }
]</textarea>

<p>Pure-Javascript solution results:
<textarea id="oupJS"></textarea>

<p>jQuery solution results:
<textarea id="oupJQ"></textarea>
Hide result
0

filterDeep deepdash lodash:

var obj = [{/* get Vijay Jagdale source object as example */}];
var idList = [2, 3];
// We will need 2 passes, first - to collect needed 'id' nodes:
var foundIds = _.filterDeep(
  obj,
  function(value, key) {
    if (key == 'id' && _.indexOf(idList, value) !== -1)
      return true;
  },
  // we need to disable condensing this time to keep all the paths in result object matching source,
  // otherwise array indexes may be changed and we will not find correct values in the source object later.
  { condense: false }
);
// second pass - to put missed 'title' nodes both for found ids and their parents.
var filtrate = _.filterDeep(obj, function(value,key,path,depth,parent,parentKey,parentPath) {
  if (_.get(foundIds, path) !== undefined ||(key == 'title' && _.get(foundIds, parentPath) !== undefined)))
    return true;
});

filtrate :

[ { title: 'category 1',
    children:
     [ { title: 'subcategory 11',
         children:
          [ { id: 2, title: 'name 2' },
            { id: 3, title: 'name 3' } ] } ] },
  { title: 'category 2',
    children:
     [ { title: 'subcategory 21',
         children: [ { id: 3, title: 'name cat2sub1id3' } ] } ] } ]

PS _.has _.get!==undefined, _.has .

0

All Articles