0

I have a dropdown in UI side and list of the objects. In this list there are lots of child objects and I need to filter all of those children. Please check below object. I am trying to do by Node JS.

 [
    {
        name : "This is horse",
        id:1
        parentId : null
    },
    {
        name : "horse child",
        id:2
        parentId : 1
    },
    {
        name : "horse child child",
        id:3
        parentId : 2
    },
    {
        name : "QQQQQ",
        id:4
        parentId : 1
    },
    {
        name : "WWWWWWWWWW",
        id:5
        parentId : 3
    },
    {
        name : "WWWWWWWWWW",
        id:6
        parentId : null
    }

]

If I select Level 0 then I get id: 1,6
If I select Level 1 then I get id: 1,2,4,6
If I select Level 2 then I get id: 1,2,3,4,5,6

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Pritesh Mahajan
  • 4,974
  • 8
  • 39
  • 64

1 Answers1

0

You should do some preprocessing on the data, so each object will get a level property. Once you have that, it is piece of cake to filter with:

result = data.filter(o => o.level <= givenLevel);

Use a tree building algorithm to populate your data with level. This code will also add a children property to each node. Maybe it can be useful:

function addLevels(data) {
    let map = new Map(data.map(o => [o.id, Object.assign(o, {children: []})])).set(null, {children: []});
    for (let o of data) map.get(o.parentId).children.push(o.id);
    (function dfs(id=null, level=-1) {
        const node = map.get(id);
        node.level = level;
        for (let child of node.children) dfs(child, level + 1);
    })();
}

// Example data
const data = [{ name : "This is horse", id:1, parentId : null }, { name : "horse child", id:2, parentId : 1 }, { name : "horse child child", id:3, parentId : 2 }, { name : "QQQQQ", id:4, parentId : 1 }, { name : "WWWWWWWWWW", id:5, parentId : 3 }, { name : "WWWWWWWWWW", id:6, parentId : null } ];

addLevels(data);

console.log(data);

You would only do this once (or every time the data changes), not every time you want to filter the data by level.

trincot
  • 317,000
  • 35
  • 244
  • 286