Reputation: 12281
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
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