How to effectively filter tree view retaining its existing structure?

前端 未结 1 1673
感动是毒
感动是毒 2021-01-01 07:33

I am having a tree structured JSON which should be filtered and the result should retain the tree structure.

var tree = [
  {
    text: \"Parent 1\",
    nod         


        
相关标签:
1条回答
  • 2021-01-01 08:15

    You could use a nested recursive approach and filter the tree, while respecting the found item.

    This solution does not mutate the original data.

    function filter(array, text) {
        const getNodes = (result, object) => {
            if (object.text === text) {
                result.push(object);
                return result;
            }
            if (Array.isArray(object.nodes)) {
                const nodes = object.nodes.reduce(getNodes, []);
                if (nodes.length) result.push({ ...object, nodes });
            }
            return result;
        };
    
        return array.reduce(getNodes, []);
    }
    
    var tree = [{ text: "Parent 1", nodes: [{ text: "Child 1", type: "Child", nodes: [{ text: "Grandchild 1", type: "Grandchild" }, { text: "Grandchild 2", type: "Grandchild" }] }, { text: "Child 2", type: "Child" }] }, { text: "Parent 2", type: "Parent" }, { text: "Parent 3", type: "Parent" }];
    
    console.log(filter(tree, 'Parent 1'));
    console.log(filter(tree, 'Child 1'));
    console.log(filter(tree, 'Grandchild 2'));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题