js根据属性过滤子树

const tree = [{
    name: "A",
    children: [{
        name: "B",
        children: [{
            name: "B1"
        },{
            name: "B2"
        },{
            name: "B3"
        }]
    }, {
        name: "C",
        children: [{
            name: "C1"
        },{
            name: "C2"
        },{
            name: "C3"
        }]
    }]
}]

const attrs = ["B1","C2"];

/**
期望返回

[{
    name: "A",
    children: [{
        name: "B",
        children: [{
            name: "B1"
        }]
    }, {
        name: "C",
        children: [{
            name: "C2"
        }]
    }]
}]
*/

function find(tree, attrs) {
    
    
}
阅读 3.5k
4 个回答
function find(tree, attrs) {
    var ret = [];
    for (var i = 0; i < tree.length && attrs.length; ++i) {
        var obj = { name: tree[i].name };
        var index = attrs.indexOf(obj.name);
        if (index >= 0) {
            ret.push(obj);
            attrs.splice(index, 1);
        }
        if (tree[i].children instanceof Array) {
            obj.children = find(tree[i].children, attrs);
            if (obj.children.length && index < 0) ret.push(obj);
        }
    }
    return ret;
}
console.dir(find(tree, ["B1", "C2"]));

这个是我根据之前的回答改的
https://segmentfault.com/q/10...
image.png

function find(list=[], attrs=[]) {
    return list.reduce((acc,cur) => {
        cur.children = find(cur.children, attrs);
        if(attrs.includes(cur.name) || cur.children.length){
            acc.push(cur);
        }
        return acc;
  }, []);
}
find(tree, attrs)

比较好理解的 find 函数;

const find = (tree, attrs) => {
    let ans = [];
    tree.forEach(t => {
        if (attrs.includes(t.name)) ans.push({name: t.name});
        else if (t.children && t.children.length) {
            let cld = find(t.children, attrs);
            if (!cld.length) return;
            t.children = cld;
            ans.push(t);
        }
    })
    return ans;
}

console.log( find(tree, ["B1", "C2"]) );
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题