Ibrahim shaikh
Ibrahim shaikh

Reputation: 343

Get All The Child Record from a tree type object array Javascript

I have one JSON data like below

var data =
[
   {
      "id":1,
      "parentId":0
   },
   {
      "id":2,
      "parentId":1
   },
   {
      "id":3,
      "parentId":1
   },
   {
      "id":4,
      "parentId":2
   },
   {
      "id":5,
      "parentId":4
   },
   {
      "id":6,
      "parentId":3
   },
   {
      "id":7,
      "parentId":6
   },
   {
      "id":8,
      "parentId":7
   }
]

now I want to get all the child of id=2 or 3

for eg: the childrens of id 2 are:(4,5) for 3: the childrens of id 2 are:(6,7,8)

how can I get all the child record

I tried using for loop but failed below is what my work

here ArrFolderTree = data;

            let parentId = [];
            let arrAdminFolder = [];
            for (let i = ArrFolderTree.length - 1; i > 0; i--) {
                let ind = 0;
                while (ind < ArrFolderTree.length) {
                    for (let o = 0; o < ArrAllFolders.length; o++) {
                        if (ArrAllFolders[o].FolderId == ArrFolderTree[ind].Id) {
                            parentId.push(ArrFolderTree[ind].Id);
                            arrAdminFolder.push(ArrFolderTree[ind].Id);
                        }
                        let currentParentId = 0;
                        for (let ab = 0; ab < parentId.length; ab++) {
                            if (parentId[ab] == ArrAllFolders[o].FolderId) {
                                currentParentId = ArrFolderTree[ind].Id;
                                arrAdminFolder.push(ArrFolderTree[ind].Id);
                            }
                        }
                        if (currentParentId > 0)
                            parentId.push(currentParentId);
                    }
                    ind++;
                }
            }

the above loop is wrong but i want to know how can i use the loop here

Upvotes: 2

Views: 986

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386726

You could take an object where all nodes are sorted by their parentId and then take the id for finding the children and the nested children by a recursion.

const
    getChildren = id => (relations[id] || []).flatMap(o => [o, ...getChildren(o.id)]),
    data = [{ id: 1, parentId: 0 }, { id: 2, parentId: 1 }, { id: 3, parentId: 1 }, { id: 4, parentId: 2 }, { id: 5, parentId: 4 }, { id: 6, parentId: 3 }, { id: 7, parentId: 6 }, { id: 8, parentId: 7 }],
    relations = data.reduce((r, o) => {
        (r[o.parentId] ??= []).push(o);
        return r;
    }, {});

console.log(getChildren(2)); // 4 5
console.log(getChildren(3)); // 6 7 8
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions