【问题标题】:JavaScript: how to filter deep JSON objectsJavaScript:如何过滤深层 JSON 对象
【发布时间】:2013-10-20 22:39:46
【问题描述】:

我有一组类似于下面的深层 JSON 对象:

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]
  }
];

所以基本上它是一个层次结构 - 有些类别可以有子类别,其中包含具有一些 ID 和名称的对象。我还有一组与最深层次结构级别(没有子对象)相关的 ID,我需要过滤这组对象,以便只保留包含已定义对象的(子)类别。

例如,如果我有一个包含两个 ID 的数组:

var IDs = [2, 3];

结果是:

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

即整体,整个“类别 2”对象被移除,整个“子类别 2”被移除,ID 为“1”的对象被移除。

问题是这些对象的深度是可变的和未知的 - 有些对象没有孩子,有些有孩子也有孩子等等,任何子类别本身都可以有一个子类别,我基本上需要找到没有孩子的对象已定义 ID 并保留每个 ID 的完整路径的子级。

谢谢。

【问题讨论】:

  • 我强烈推荐Underscore(或 Lodash)——它会让你的生活更轻松
  • @Bojangles - 下划线很棒,但它究竟如何帮助我解决这个特定问题?我可能会遗漏一些东西,但我没有看到任何下划线方法可以做到这一点。谢谢。
  • 抱歉,我在打电话,没有正确阅读问题。我看到很多复杂的对象迭代立即想到了下划线

标签: javascript json


【解决方案1】:

基本上,对树执行深度优先遍历,在每个节点上调用回调函数。如果该节点是叶节点并且它的 ID 出现在您的列表中,然后克隆通向该叶的分支,但不要重新克隆该分支的任何部分已经克隆了。

构建树的部分副本和过滤副本后,您需要清理原始副本。为了记账目的,我在此过程中对原始树进行了变异 - 跟踪哪些分支已经被克隆。

编辑:修改代码以过滤树列表而不是单个树

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);

【讨论】:

  • 谢谢你,迈克,但我不确定我是否明白这应该如何工作。尤其是您创建 root.copied 的那部分 - root 应该是数据层次结构的顶层,这是一个包含多个对象的数组,其中有多个对象,对吧?我可能错过了一些东西。
  • 再次查看您的代码我看到您正在处理一个树列表,而我的代码处理一棵树。将代码包装在 for 循环中以遍历列表应该可以做到。请参阅上面的编辑。
【解决方案2】:

您可以使用deepdash 扩展中的filterDeep 方法lodash

var obj = [{/* get Vijay Jagdale's source object as example */}];
var idList = [2, 3];
var found = _.filterDeep(
  obj,
  function(value) {
    return _.indexOf(idList, value.id) !== -1;
  },
  { tree: 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' } ] } ] } ]

这是您的用例的full working test

【讨论】:

    【解决方案3】:

    虽然这是一个老问题,但我会加我的 2 美分。该解决方案需要通过循环、子循环等进行直接迭代,然后比较 ID 并构建结果对象。我有纯 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>

    【讨论】:

      【解决方案4】:

      我不会重新发明轮子。我们现在使用object-scan 进行大部分数据处理,它很好地解决了您的问题。方法如下

      // const objectScan = require('object-scan');
      
      const filter = (input, ids) => {
        objectScan(['**[*]'], {
          filterFn: ({ value, parent, property }) => {
            if (
              ('id' in value && !ids.includes(value.id))
              || ('children' in value && value.children.length === 0)
            ) {
              parent.splice(property, 1);
            }
          }
        })(input);
      };
      
      const 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: [] } ];
      
      filter(hierarchy, [2, 3]);
      
      console.log(hierarchy);
      // => [ { title: 'category 1', children: [ { title: 'subcategory 1', children: [ { id: 2, title: 'name 2' }, { id: 3, title: 'name 3' } ] } ] } ]
      .as-console-wrapper {max-height: 100% !important; top: 0}
      &lt;script src="https://bundle.run/object-scan@13.8.0"&gt;&lt;/script&gt;

      免责声明:我是object-scan的作者

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-25
        • 1970-01-01
        相关资源
        最近更新 更多