I have problem with nested object in javascript. I want to generate, lets say, tree of objects. For example I have tree like this:
var tree = {
item1: {
item11: {},
item12: {}
},
item2: {
item21: {
item211: {},
item212: {}
}
}
}
Now I have path in string (like item1.item11
) and I want to put item111
to tree
object using path
.
After calling treePush
function I want this:
var tree = {
item1: {
item11: {
item111: {}
},
item12: {}
},
item2: {
item21: {
item211: {},
item212: {}
}
}
}
For now I have this piece of code, but this puts new item into root of tree
not into desided level:
//use example: treePush('item1.item11', 'item111', tree);
function treePush(path, value, tree) {
var branch = getBranch(path, tree);
branch[value] = {};
$.extend(tree, branch);
return tree;
}
function search(key, tree) {
//searches key in tree and generates path like 'item1.item11'
}
function getBranch(path, tree) {
var keys = path.split('.'),
obj = tree,
branch = {};
for(var i = 0; i < keys.length - 1; i++) {
var key = keys[i];
if (obj[key] === undefined) {
return {};
}
branch[key] = obj[key];
obj = obj[key];
}
return branch;
};
I think the problem is in line #5 of treePush
function (branch[value] = {};
) but I can't make it working. Any help appreciated.