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 i can to create nested childs from array of elements?

This is the given array:

array = [{number : 1 , name : 'one' , child : [] },{number : 2, name : 'two' , child : []},{number : 3 , name : 'three' , child : []}]

How to create nested child objects in JavaScript from this array?

nested = [
 {
  number : 1,
  name : 'one',
  child : [
   {
    number : 2,
    name : 'two',
    child : [{
     number : 3,
     name : 'three',
     child : []
      }
     ]
   }
  ]
 }
]

i try to solve this but i cant do this

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 :

You can use the array.reduceRight method to achieve your result.

Here’s how you can do it:

const array = [
  { number: 1, name: 'one', child: [] },
  { number: 2, name: 'two', child: [] },
  { number: 3, name: 'three', child: [] }
];

const nested = array.reduceRight((a, b) => {
  b.child.push(a);
  return b;
});

console.log(JSON.stringify(nested, null, 2));

JSON.stringify() The third argument enables pretty printing and sets the spacing

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