我有一个 json 对象,如下所示。
[{
"data":{
"title":"Root"
},
"attr":{
"id":1,
"parentId":0
},
"state":"open",
"children":[{
"data":{
"title":"Stem"
},
"attr":{
"id":11,
"parentId":1
},
"state":"open",
"children":[{
"data":{
"title":"Branch 1"
},
"attr":{
"id":111,
"parentId":11
},
"state":"open",
"children":[{
"data":{
"title":"Sub Branch 1"
},
"attr":{
"id":1111,
"parentId":111
},
"state":"open",
"children":[{
"data":{
"title":"Leaf"
},
"attr":{
"id":111111,
"parentId":111
}
}]
},
{
"data":{
"title":"Sub Branch 2"
},
"attr":{
"id":111111,
"parentId":111
}
}
]
},
{
"data":{
"title":"Branch 2"
},
"attr":{
"id":119,
"parentId":11
},
"state":"open",
"children":[{
"data":{
"title":"Sub branch"
},
"attr":{
"id":120,
"parentId":119
}
}
]
}
]
}
]
}]
基本上结构是这样的
我有属性(attr)中所有节点的ID。 当给定任何节点的 ID 时,我想获取该节点及其子节点的 json。
例如。对于给定的 ID(例如 111),该 ID 及其子项的 json 为
{
"data":{
"title":"Branch 1"
},
"attr":{
"id":111,
"parentId":11
},
"state":"open",
"children":[{
"data":{
"title":"Sub Branch 1"
},
"attr":{
"id":1111,
"parentId":111
},
"state":"open",
"children":[{
"data":{
"title":"Leaf"
},
"attr":{
"id":111111,
"parentId":111
}
}]
},
{
"data":{
"title":"Sub Branch 2"
},
"attr":{
"id":111111,
"parentId":111
}
}
]
}
我想在输入 id 111 时获取此 json。我该怎么做?
编辑:考虑我有一个 GUI 来输入节点的 ID。并说我输入 111 我应该能够得到上面的 json 。 我只需要如何在 js 或 jQuery 中做到这一点。我不关心用户界面。
谢谢!
最佳答案
function getNodeById(nodes, wantId) {
var search = nodes.slice(0);
while (node = search.shift()) {
if (node.attr.id == wantId) {
return node;
}
if (node.children) {
search.push.apply(search, node.children);
}
}
return false;
}
如果您将对象的任何级别传递给它,它将递归搜索该对象和子对象,直到找到匹配的 ID,否则将返回 false。
调用函数:
var node = getNodeById(myArray, 1111);
console.log(node);
关于javascript - 迭代并获取 json 的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16933052/