Can't convert Javascript array to object properly
I have bee开发者_StackOverflown struggling with this problem the entire day. I feel like it's super solvable, and I'm not sure where I'm going wrong. Each time I go to post this, I feel like I come up with a different solution that doesn't end up working.
I'm looking to do the following:
var someObj = {};
// @param key - string - in the form of "foo-bar-baz" or "foo-bar".
// (i won't know the number of segments ahead of time.)
// @param value - string - standard, don't need to act on it
function buildObject( key, value ) {
var allKeys = key.split("-");
// do stuff here to build someObj
}
Essentially the key will always take the format of key-key-key where i want to build someObj[key1][key2][key3] = value
.
This JSFiddle contains a longer example with a sample layout of the data structure I want to walk away with.
Thanks so much for any help you can give.
var someObj = {};
// @param key - string - in the form of "foo-bar-baz" or "foo-bar".
// (i won't know the number of segments ahead of time.)
// @param value - string - standard, don't need to act on it
function buildObject( key, value ) {
var allKeys = key.split("-");
var container, i, n;
for (container = someObj, i = 0, n = allKeys.length; i < n - 1; ++i) {
var keyPart = allKeys[i];
container = Object.hasOwnProperty.call(container, keyPart)
? container[keyPart] : (container[keyPart] = {});
}
container[allKeys[n - 1]] = value;
}
I came up with http://jsfiddle.net/XAn4p/ before i saw Mike's answer. I'm posting just for another way.
var newObj = function ()
{};
newObj.prototype =
{
addToObject: function (keys, value)
{
var keySplit = keys.split("-",2);
if (keySplit.length > 1)
{
if(this[keySplit[0]] == null)
{
this[keySplit[0]] = new newObj();
}
var newKeys = keys.substr(keySplit[0].length +1);
this[keySplit[0]].addToObject(newKeys, value);
}
else
{
this[keySplit[0]] = value
}
}
};
var obj = new newObj();
精彩评论