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' { } } }
object.key
in the first parameter. – Honus Wagner Feb 21 '13 at 17:02