I have a javascript object like below:
{
type: "ul",
id: "1",
children: [
{
type: "li",
id: "2",
children: [
{
type: "ul",
id: "3",
children: [...]
}
]
}
]
}
I want to turn it into:
{
type: "ul",
id: "1",
children: [
{
type: "li",
id: "2",
parentId: "1",
children: [
{
type: "ul",
id: "3",
parentId: "2",
children: [...]
}
]
}
]
}
There can be infinite nesting in the children's array and it should add parentId to only who have a parent and stop if the children's array is empty or the key doesn't exists
CodePudding user response:
Here's a recursive solution:
const obj={type:"ul",id:"1",children:[{type:"li",id:"2",children:[{type:"ul",id:"3"}]}]};
function setIds(obj, parent) {
if (parent) {
obj.parentId = parent.id;
}
obj?.children?.forEach(e => setIds(e, obj))
}
setIds(obj)
console.log(obj)
.as-console-wrapper{top:0;max-height: 100%!important}
CodePudding user response:
Shouldn't be any more complex than
const parentify = (parent, parentId) => ({
...parent,
parentId,
children: parent.children.map( child => parentify(child, parent.id ) ),
});
Kick it off with:
const newObject = parentify( originalObject ) ;