skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can use recursion to solve this problem.

    Here’s how you can do it:

    const nested = array.reduceRight((a, b) => ({
      ...b,
      child: [{...a}]
    })
    )
    

    I hope this answer can help you even a little.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search