Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get parent object property in child

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading