Create a dynamic nested object from array of properties

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);

Leave a Comment