Skip to content Skip to sidebar Skip to footer

How To Effectively Filter Tree View Retaining Its Existing Structure?

I am having a tree structured JSON which should be filtered and the result should retain the tree structure. var tree = [ { text: 'Parent 1', nodes: [ { tex

Solution 1:

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

This solution does not mutate the original data.

functionfilter(array, text) {
    constgetNodes = (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; }

Post a Comment for "How To Effectively Filter Tree View Retaining Its Existing Structure?"