locrizak
locrizak

Reputation: 12281

Building an object from array in javascript

What I have is an array like this: ['foo','bar'] and I want to turn it into an object that looks like this:

{
     foo:{
          bar:{
               etc:{}
          }
     }
}

I've tried with two loops but I can get it to work if there is three values in the array.

Upvotes: 0

Views: 55

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219930

var obj = {};
var pointer = obj;

array.forEach(function (item) {
    pointer = pointer[item] = {};
});

Here's the fiddle: http://jsfiddle.net/h67ts/


If you have to support IE < 9, you can either use a regular loop, or use this polyfill:

if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}

Upvotes: 5

Related Questions