javascriptarraysobject

Create a dynamic nested object from array of properties


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?


Solution

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