0

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.

5
  • 1
    What do you want it to look like with three values in the array? Commented Jan 31, 2013 at 19:30
  • 1
    So show us what you have tried. Commented Jan 31, 2013 at 19:30
  • Will there always be two values? What should it look like if not? Commented Jan 31, 2013 at 19:31
  • Are you trying to convert into JSON by any chance? Commented Jan 31, 2013 at 19:32
  • not parsing json, updating what it should be if there is more values Commented Jan 31, 2013 at 19:34

1 Answer 1

5
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);
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

IE says he does not like forEach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.