I have an array of nested objects, having parent-child relationship:
[
{
"id":"5b9ce8d51dbb85944baddfa5",
"name":"EARBANG",
"parent_id":0,
"status":"Inactive",
"children":[
{
"id":"5b9ce8d5d978f75e4b1584ba",
"name":"DIGINETIC",
"parent_id":"5b9ce8d51dbb85944baddfa5",
"status":"Active",
"children":[
{
"id":"5b9ce8d5cb79d63c8b38018c",
"name":"PREMIANT",
"parent_id":"5b9ce8d5d978f75e4b1584ba",
"status":"Active",
}
]
}
]
},
{
"id":"5b9ce8d51650fac75fa359c8",
"name":"GEEKOLOGY",
"parent_id":0,
"status":"Active",
},
{
"id":"5b9ce8d59f52e801a2e40a97",
"name":"TOYLETRY",
"parent_id":0,
"status":"Inactive",
},
{
"id":"5b9ce8d5d136fcfed2f3e0dd",
"name":"PAPRIKUT",
"parent_id":0,
"status":"Inactive",
},
{
"id":"5b9ce8d53afb7a61e188c48e",
"name":"EYERIS",
"parent_id":0,
"status":"Inactive",
}
]
here I want that :
1- Find an object having id e.g. 5b9ce8d51dbb85944baddfa5
2- iterate in that objects children array (if non empty) recursively and get id of all its childrends and grand-childrens and great-grand-childrens in an array.
So my result will be like
{
"id":"5b9ce8d51dbb85944baddfa5",
childs: ["5b9ce8d5d978f75e4b1584ba", "5b9ce8d5cb79d63c8b38018c", ...]
}
I tried some solutions available on stack overflow, but could not get it to work.
I appreciate if anyone can help me, my DS not that strong.
Thanks
Here is a search recursive function:
function searchRecursive(data, id) {
let found = data.find(d => d.id === id);
if (!found) {
let i = 0;
while(!found && i < data.length) {
if (data[i].children && data[i].children.length) {
found = searchRecursive(data[i].children, id);
}
i++;
}
}
return found;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With