在我的应用程序中,我基于来自服务器的 JSON 响应创建了一个 JavaScript 对象,类似于:
{
name: "root",
id: 1,
children: [
{
name: "child one",
id: 11,
children: [
{name: "grand child 1", id: 111, children: []},
{name: "grand child 2", id: 112, children: []}
]
},
{
name: "child two",
id: 12,
children: []
}
]
}
我创建了一个新节点,例如:
{name: "grandchild three", id: 113, children:[]}
考虑到这一点,我如何将这个新的孙子添加到其 ID 为 11 的父级?请注意,我不知道带有 id == 11
的节点的静态路径,所以我想知道如何在知道它是 id
的情况下获取该节点。
编辑:请注意,在实际情况下,id 不会对对象的路径进行编码。我创建了这个简单的示例来演示我正在处理的数据结构。但是我无法在我的实际应用程序中使用对象的 ID 检索对象的路径。
最佳答案
请参阅此 fiddle :http://jsfiddle.net/2Dvws/
它将通过 ID 找到一个对象。并插入新的 child 。由于 Javascript 中的每个对象都是一个引用,您可以将其作为 var 返回。
var ob = {
name: "root",
id: 1,
children: [
{
name: "child one",
id: 11,
children: [
{
name: "grand child 1",
id: 111,
children: []},
{
name: "grand child 2",
id: 112,
children: []}
]},
{
name: "child two",
id: 12,
children: []}
]
};
返回找到的元素的函数。将查看所有子元素。
function findObjectById(root, id) {
if (root.children) {
for (var k in root.children) {
if (root.children[k].id == id) {
return root.children[k];
}
else if (root.children.length) {
return findObjectById(root.children[k], id);
}
}
}
};
var bla = findObjectById(ob, 111);
console.log(bla);
bla.children.push({
name: "child x",
id: 1111,
children: []
});
console.log(ob);
输出是 id 为 111 的 child 将有 1 个 id 为 1111 的 child
关于javascript - 如何使用父 id 将对象添加到嵌套的 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899609/