【问题标题】:recursive json tree filter递归 json 树过滤器
【发布时间】:2017-02-07 15:11:47
【问题描述】:

我正在使用 Angular 1.5.9,并且我有一个这样的 JSON 对象:

var data=[
    {"id":1,"name":"object 1", childs:[

        {"id":51,"name":"object 51", childs:[]},
    ]},
    {"id":2,"name":"object 2", childs:[
        {"id":11,"name":"object 11", childs:[]},
        {"id":12,"name":"object 12", childs:[
            {"id":13,"name":"object 100", childs:[]},
        ]},
    ]},
    {"id":3,"name":"object 3", childs:[]},
    {"id":1,"name":"object 1", childs:[]}
];

我需要过滤这棵树,以便获得所有元素(名称包含过滤字符串的分支或叶子以及所有父元素。 即:过滤“100”将导致

[
    {"id":2,"name":"object 2", childs:[
        {"id":12,"name":"object 12", childs:[
            {"id":13,"name":"object 100", childs:[]},
        ]},
    ]},
]

然后,这些数据将在自定义树指令中使用 ng-repeat 对数据本身进行渲染

我想知道是否有人可以提出一种干净有效的方法来实现这一目标。我写的所有代码似乎都太复杂了,最终遍历树的次数太多了,必须有更好的方法。

实际的元代码有点像 * 依次读取主数组中的 ech JSON 对象 * 如果名称匹配,则添加一个属性(可见:true)并返回开始设置所有父母的可见:trre * 如果childs数组包含一些东西,重新调用主过滤函数扫描所有childs

这对于小型数据集可能是可以接受的,但在大型对象上可能会非常低效。

【问题讨论】:

标签: angularjs json


【解决方案1】:

您可以为此编写一些递归 javascript,例如:

function findObjectAndParents(item, name) {
    if (item.name.split(' ')[1] == name) {
        return true;
    }

    for (var i = 0; i < item.childs.length; i++) {
        if (findObjectAndParents(item.childs[i], name)) {
            return true;
        }
    }

    return false;
}

并像这样使用它:

var searchName = "100";
var filtered = data.filter(function(item) {
    return findObjectAndParents(item, searchName);
});

【讨论】:

    【解决方案2】:

    参考答案:
    A Javascript function to filter tree structured json with a search term. exclude any object which donot match the search term

    function search(array, name) {
        const s = (r, { childs, ...object }) => {
            if (object.name.includes(name)) {
                r.push({ object, childs: [] });
                return r;
            }
            childs = childs.reduce(s, []);
            if (childs.length) r.push({ ...object, childs });
            return r;
        };
        return array.reduce(s, []);
    }
    
    
    console.log(JSON.stringify(search(data, '100'),0,2));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多