Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dynamic nested object from array of properties

Tags:

This sounds like a simple task, but I can't quite figure it out: I have an array :

var array = ['opt1','sub1','subsub1','subsubsub1'] 

From that I want to generate the following objects:

{   opt1:{     sub1:{       subsub1:{         subsubsub1:{}       }     }   } } 

I have a way to do it, making a string and using eval, but I'm looking to avoid that, any idea?

like image 318
xShirase Avatar asked Mar 21 '14 15:03

xShirase


People also ask

How do I create a nested object in JavaScript?

const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.

How do you change the properties of an array of objects?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!


1 Answers

You could use reduce:

var array = ['opt1','sub1','subsub1','subsubsub1'];  var object = {};  array.reduce(function(o, s) { return o[s] = {}; }, object);  console.log(object);

But this was only introduced in ECMAScript 5.1, so it won't be supported in some older browsers. If you want something that will be supported by legacy browsers, you could use the polyfill technique described in the MDN article above, or a simple for-loop, like this:

var array = ['opt1','sub1','subsub1','subsubsub1'];  var object = {}, o = object;  for(var i = 0; i < array.length; i++) {      o = o[array[i]] = {};  }  console.log(object);
like image 73
p.s.w.g Avatar answered Oct 27 '22 14:10

p.s.w.g