我对 javascript 中的嵌套对象有疑问。我想生成,比如说,对象树。例如我有这样的树:
var tree = {
item1: {
item11: {},
item12: {}
},
item2: {
item21: {
item211: {},
item212: {}
}
}
}
现在我在字符串中有路径(如),我item1.item11
想item111
使用.tree
path
调用treePush
函数后,我想要这个:
var tree = {
item1: {
item11: {
item111: {}
},
item12: {}
},
item2: {
item21: {
item211: {},
item212: {}
}
}
}
现在我有这段代码,但这会将新项目放入根目录中,tree
而不是放入指定级别:
//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;
};
我认为问题出在treePush
函数(branch[value] = {};
)的第 5 行,但我无法使其正常工作。任何帮助表示赞赏。