Home > Back-end >  How to create nested objects by returning objects in array with reduce in js
How to create nested objects by returning objects in array with reduce in js

Time:10-30

I have an array, how to create a new object in another object by nesting each element of this array

let newArr = ['Parent', 'Child']

I want to convert this array to this format

  Parent[Child]={}

I should be able to loop this array and format it according to the length of the array

CodePudding user response:

['a', 'b', 'c'].reduceRight((nest, key) => ({ [key]: nest }), {});
// { a: { b: { c: {} } } }
  • Related