如何过滤/搜索返回父和子的嵌套树

时间:2017-04-29 06:05:59

标签: javascript

我有一个嵌套列表,看起来像这样:

list = {
"name": "first",
"children": [
    "name" : "second",
    "children" : [
        "name" : "third",
        "children" : [...could be nested infinitly]
    ]
],
"name": "a",
"children": [
    "name" : "b",
    "children" : [
        "name" : "c",
        "children" : [...could be nested infinitly]
    ]
],
"name": "test",
"children": [
    "name" : "testChild",
    "children" : [
        "name" : "grandChild",
        "children" : [...could be nested infinitly]
    ]
]

}

我正在努力解决的问题是使用AND OR CONTAINS进行查询/过滤/搜索的最佳方式:

Name CONTAINS a AND children > 2 OR name = grandchild

哪会回来:

newList = {
"name": "a",
"children": [
    "name" : "b",
    "children" : [
        "name" : "c",
        "children" : [...could be nested infinitly]
    ]
],
"name": "test",
"children": [
    "name" : "testChild",
    "children" : [
        "name" : "grandChild",
        "children" : [...could be nested infinitly]
    ]
]

}

1 个答案:

答案 0 :(得分:1)

您可以为子项使用约束函数和迭代递归方法。结果集返回与所有属性匹配的第一个节点。

function getList(array, constraint) {
    var result = [];
    array.forEach(function iter(a) {
        constraint(a) && result.push(a);
        Array.isArray(a.children) && a.children.forEach(iter);
    });
    return result;
}


var list = [{ name: "first", children: [{ name: "second", children: [{ name: "third", children: [] }] }, { name: "a", children: [{ name: "b", children: [{ name: "c", children: [] }] }, { name: "test", children: [{ name: "testChild", children: [{ name: "grandChild", children: [] }] }] }] }] }],
    constraint = function (o) {
        return o.name.indexOf('a') !== -1 && (o.children || []).length === 2 || o.name === 'grandChild';
    };

console.log(getList(list, constraint));
console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题