从父子 JSON 数据中获取所有子项 [英] Get all children from parent child JSON data
问题描述
我有父子 JSON 数据,我想从选定的父项中获取所有子项(嵌套子项).
I have parent-child JSON data and I want get all children (nested children) from selected parent.
例如,我有 JSON 数据:
For example, I have JSON data :
[{
"id": 1,
"parent": 0,
"name": "Parent"
}, {
"id": 2,
"parent": 1,
"name": "Child 1"
}, {
"id": 3,
"parent": 2,
"name": "Grand Child 1"
}, {
"id": 4,
"parent": 2,
"name": "Grand Child 2"
}, {
"id": 5,
"parent": 1,
"name": "Child 2"
}]
我有函数 findAllChildren(1),其中1"是父",然后函数的结果应该是:
And I have function findAllChildren(1), where "1" is "parent" and then result of function should be :
[{
"id": 2,
"parent": 1,
"name": "Child 1"
}, {
"id": 3,
"parent": 2,
"name": "Grand Child 1"
}, {
"id": 4,
"parent": 2,
"name": "Grand Child 2"
}, {
"id": 5,
"parent": 1,
"name": "Child 2"
}]
在其他情况下,如果我调用 findAllChildren(2),函数的结果应该如下所示:
And in other case, if i call findAllChildren(2), result of the function should like below :
[{
"id": 3,
"parent": 2,
"name": "Grand Child 1"
}, {
"id": 4,
"parent": 2,
"name": "Grand Child 2"
}]
创建函数来解决这种情况的正确方法是什么?谢谢.
What is the proper way to create function to solve that case? Thank you.
推荐答案
您可以遍历原始数据并查找具有指定 id 为 parent_id 的项目.如果找到,则对元素的 id 递归执行相同操作.
You can just iterate over the original data and look for items that has the specified id as parent_id. If found, do the same recursively with the element's id.
在这里查看:https://jsfiddle.net/6ydog1tj/2/>
function findAllChildren (id, results, depth) {
for (d in data) {
if (data[d].parent == id) {
data[d].depth = depth
results.push(data[d])
findAllChildren(data[d].id, results, depth + 1)
}
}
}
var results = []
findAllChildren(1, results, 0)
$('body').append(results.map(function (element) { return Array(element.depth + 1).join(' -> ') + element.name + '<br>' }))
console.log(results)
打印出来
Child 1
-> Grand Child 1
-> Grand Child 2
Child 2
这篇关于从父子 JSON 数据中获取所有子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!