从json获取所有子节点 [英] get all child nodes from json
问题描述
我有以下json:
var source=[{'k':'01'},
{'k':'02', 'children': [
{'k':'05'},
{'k':'06', 'children': [
{'k':'ABC'},
{'k':'PQR'}
]},
{'k':'07'}
]},
{'k':'03'}];
我希望能够为k指定一个值,并取回所有的孩子(以及孙子和曾孙等).
I want to be able to specify a value for k and get back all of the children (and grandchildren and great-grandchildren, etc.).
例如,如果我提供'02'
,我想接收
For instance if I provide '02'
, I want to receive
[
{'k':'05'},
{'k':'06'},
{'k':'ABC'},
{'k':'PQR'},
{'k':'07'}
]
推荐答案
尝试以下操作:
function mergeChildren(sources) {
var children = [];
for (var index in sources) {
var source = sources[index];
children.push({k: source.k});
if (source.children) {
children = children.concat(mergeChildren(source.children))
}
}
return children;
}
function findChildrenForK(sources, k) {
for (var index in sources) {
var source = sources[index];
if (source.k === k) {
if (source.children) {
return mergeChildren(source.children);
}
}
}
}
findChildrenForK
扫描对象数组sources
,并将其属性k
与提供给该函数的k
进行匹配.如果找到匹配的对象,则在该对象的children
属性上调用mergeChildren
.
findChildrenForK
scans through an array of objects, sources
, and matches their property k
to the k
supplied to the function. If a matching object is found, we call mergeChildren
on that object's children
property.
mergeChildren
遍历分配给它的对象数组,并将每个键推入称为children
的数组.如果任何对象本身都有子对象,则通过递归调用mergeChildren
并使用
mergeChildren
iterates through the array of objects given to it, and pushes each key into an array, called children
. If any objects themselves have children, we concatenate them to our children
accumulator by calling mergeChildren
recursively and using the Array#concat function.
在此 JSFiddle 中查看包含您的示例数据的实际脚本.
See the script in action with your sample data in this JSFiddle.
这篇关于从json获取所有子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!