Nesting keys of an array in a Javascript object

Asked

Viewed 322 times

1

How to create a nested javascript object 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 to iterate within a loop. But I can’t find a way to validate whether the result already exists or not, nor put in the correct position, one key inside another.

  • Take a look at the underscore.js. library It makes array treatments a lot easier.

1 answer

2


To do exactly as you ask, iterate the array and create sub objects. You can do so:

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: http://jsfiddle.net/nxq9108x/

This works because in Javascript you can pass objects by reference between variables. So when I do temp[x[i]] = {}; is the same as doing y[x[i]] = {}; in the first iteration.

Then how do I temp = temp[x[i]]; I’m changing the reference of which part of the object the variable temp is pointing. And so I’m creating the sub-objects.

  • 1

    That’s exactly what it was.

  • 1

    @Marceloaymone great, I’m glad I helped.

  • @Sergio Could you do that with the .reduce()?

  • The only thing, though, is that if I do this inside another loop, one key overwrites the other...

  • 1

    @Maiconcarraro sim daria (http://jsfiddle.net/4jz3q4yk/)

  • @Marceloaymone how so? You can comment with an example in jsFiddle (using my example)?

  • I was having trouble with that @Sergio, I didn’t notice that I had to pass the y no }, y);, i was assigning the reduce return :~

  • It is possible, just declare the Y out of the loop. The idea is to create multidimensional arrays from an array of objects, without repeating the keys, but using your example worked yes.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.