Skip to content Skip to sidebar Skip to footer

Populate Nested Object From Array?

I have a question, how to create nested object from array? I.e. I have a following array: var myArr = ['foo', 'bar', 'baz'] and need to make it an object like: myObj = {foo: { bar:

Solution 1:

Use reduce()

var myArr = ['foo', 'bar', 'baz'];
var myObj = {};

myArr.reduce(function(a, b) {
  a[b] = {};
  return a[b];
}, myObj);

console.log(myObj);

Solution 2:

you can do better ! :

let arr = ['foo', 'bar', 'baz'];

let obj = arr.reduceRight((a,c)=>({[c]:a}),{})

document.write( JSON.stringify(obj) )

Using .reduceRight() method


Post a Comment for "Populate Nested Object From Array?"