I have a nested object with the dynamic depth. I need to slightly alter it's structure.
For example I have an object like this :
let root = {
data:{
id:"5df6608a-59f0-42ac-9c2e-fb2a53df9008",
name:"Product"
},
children:[
{
data:{
id:"b527b1f5-4fd5-4f11-b4f1-6deeb33473d8",
name:"productId"
},
children:[
{
data:{
id:"7045051e-b97e-4836-9048-e93d72c75751",
name:"rating"
},
children:[
{
data:{
id:"88025b92-4309-4864-9c40-d4effd33a38b",
name:"ratingId"
},
children:[
]
}
]
}
]
}
]
}
The root object contains an object called data and an array of children which in turn has the same structure as the root object i need to remove the data object and move the id and name values which is inside the data object to the same level as children array as shown below.
let root = {
id:"5df6608a-59f0-42ac-9c2e-fb2a53df9008",
name:"Product",
children:[
{
id:"b527b1f5-4fd5-4f11-b4f1-6deeb33473d8",
name:"productId",
children:[
{
id:"7045051e-b97e-4836-9048-e93d72c75751",
name:"rating",
children:[
{
id:"88025b92-4309-4864-9c40-d4effd33a38b",
name:"ratingId",
children:[
]
}
]
}
]
}
]
}
How can i do it using javascript?
So for i have written a method using which i can traverse the object up to depth of two levels but the object's depth is dynamic.
Below is the code that i have written in reactjs.
formateTreeChlidren(treeData){
let rootObject = {
name: treeData.data.name,
id: treeData.data.id,
children: []
}
let tempArray= [];
treeData.children.map( child => {
let childrenArray = [];
if(child.children.length > 0){
child.children.map( subChild => {
let subChildObject= {
name: subChild.data.name,
id: subChild.data.id,
children:subChild.children
}
childrenArray.push(subChildObject);
});
}
let childObject= {
name: child.data.name,
id: child.data.id,
children:childrenArray
}
tempArray.push(childObject);
});
rootObject["children"] = tempArray;
}