I apparently cannot think abstractly enough to do this... but I'd like to create a Javascript object out of an array that uses the array values as property names, but they should be nested objects within each other.
So if I had an array like this:
['First', 'Second', 'Third', 'Fourth']
My expected output would be:
{
First: {
Second: {
Third: {
Fourth: {}
}
}
}
}
UPDATE Here is the function I was using as mentioned in the commment:
function appendKey(obj, to, key) {
if (obj.hasOwnProperty(to)) {
appendKey(obj[to], to, key);
} else {
obj[key] = {};
}
return obj;
}
My intent was to call it as such:
var data = ['First', 'Second', 'Third', 'Fourth'];
data = appendKey(data, 'First', 'Second');
data = appendKey(data, 'Second', 'Third');
data = appendKey(data, 'Third', 'Fourth');
Clearly that could be put into a loop, which is why I wanted to do it that way. My output ended up being:
data = { 'First' : { 'Second' } } // it works this time!
data = { 'First' : { 'Second' },
'Third' : { } }
data = { 'First' : { 'Second' },
'Third' : { 'Fourth' { } } }
2 Answers 2
Outside the loop, store your base object in a variable, and have a separate variable to store the current object (which starts off being the same as the base).
Inside the loop, take the "current" object, give it a key using the current array member, assign a new object to that key, and make that new object the new "current" object.
var arr = ['First', 'Second', 'Third', 'Fourth'],
obj = {},
currObj = obj;
arr.forEach(function(key) {
currObj = (currObj[key] = {});
});
console.log(obj); // {First:{Second:{Third:{Fourth:{}}}}}
DEMO: http://jsfiddle.net/qunDt/
You can unwind the code in the forEach a bit if you prefer.
arr.forEach(function(key) {
currObj[key] = {};
currObj = currObj[key];
});
If you wanted a purely recursive approach, you could do it like this:
function nested(list, o) {
if (list.length === 0)
return o;
o[list.shift()] = nested(list, {})
return o;
}
var obj = nested(arr, {});
Comments
var names = ['First', 'Second', 'Third', 'Fourth'];
var build = function(soFar,remaining) {
if(remaining.length === 0) {return soFar;}
var outer = {};
outer[names.pop()] = soFar;
return build(outer, names);
}
var result = build({}, names);
Comments
Explore related questions
See similar questions with these tags.
object.keyin the first parameter.