MockingBirds
MockingBirds

Reputation: 47

How to create nested child objects in JavaScript from array?

This is the given array:

[{
  key: 1,
  nodes: {}
}, {
  key: 2,
  nodes: {}
}, {
  key: 3,
  nodes: {}
}]

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

[{
  key: 1,
  nodes: [{
    key: 2,
    nodes: [{
      key: 3,
      nodes: []
    }]
  }]
}];

Upvotes: 0

Views: 103

Answers (2)

Senthil
Senthil

Reputation: 777

It's working fine. Try this below code

  const firstArray = [{ key: 1, nodes: {} }, { key: 2, nodes: {} }, { key: 3, nodes: {} }];
firstArray.reverse();
const nestedObject = firstArray.reduce((prev, current) => {
    return {
        ...current,
            nodes:[{...prev}]
    }
}, {});

console.log(nestedObject)

Upvotes: 0

Mark
Mark

Reputation: 92440

This is a pretty good use case for reduceRight which allows you to build the structure from the inside out:

let arr = [{
  key: 1,
  nodes: {}
}, {
  key: 2,
  nodes: {}
}, {
  key: 3,
  nodes: {}
}]

let a = arr.reduceRight((arr, {key}) => [{key, nodes: arr}],[])

console.log(a)

Upvotes: 9

Related Questions