Sorry my english is not good, hope everyone understand. I have an array:
var data=[
{
"id": 2,
"parent_id": 1
},
{
"id": 3,
"parent_id": 2
},
{
"id": 7,
"parent_id": 3
},
{
"id": 67,
"parent_id": 1
}
]
And this is what I need the result to look:
[
{
"id": 2,
"parent_id": 1,
"child":[
{
"id": 3,
"parent_id": 2,
"child":[{
"id": 7,
"parent_id": 3
},
]}
]},
{
"id": 67,
"parent_id": 1
},]
My idea is: 1 method has 2 parameters of the same array. I use nested loop. If parent_id == id will add the field "child".
const getTree = function(data, maindata){
const result=data.forEach(item =>{
const child=maindata.forEach(element =>{
if(item.id === element.parent_id){
return true;
}
return false
})
getTree(child, maindata)
item.child = child;
})
return result;
}
console.log(getTree(data,data))
But it is not working as it should. Hope everybody help please. thanks