Nest keys in an array in a Javascript object

1

How to create a javascript object nested from a literal array?

I have the following array:

var x = ['a','b','c'];

From the array 'x' I would like to generate the following object:

var y = {a:{b:{c:{}}}};

So far I've tried iterating inside a loop. But I can not find a way to validate whether the result already exists or not, nor put in the correct position, a key within another.

    
asked by anonymous 24.06.2015 / 21:54

1 answer

2

To do exactly as you ask, you need to iterate through the array and create sub objects. You can do this:

var x = ['a', 'b', 'c'];

var y = {};
var temp = y;
for (var i = 0; i < x.length; i++) {
    temp[x[i]] = {};
    temp = temp[x[i]];
}

jsFiddle: link

This works because in JavaScript objects can be passed by reference between variables. So when I do temp[x[i]] = {}; it's the same as doing y[x[i]] = {}; in the first iteration.

Then how do I temp = temp[x[i]]; change the reference of which part of the object the temp variable is pointing to. And so I create the sub-objects.

    
24.06.2015 / 22:07