从父子JSON数据中获取所有子项

Hid*_*yat 6 javascript algorithm search jquery json

我有父子JSON数据,我希望从所选父项中获取所有子项(嵌套子项).

例如,我有JSON数据:

[{
  "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"
}]
Run Code Online (Sandbox Code Playgroud)

我有函数findAllChildren(1),其中"1"是"父",然后函数的结果应该是:

[{
  "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"
}]
Run Code Online (Sandbox Code Playgroud)

而在其他情况下,如果我调用findAllChildren(2),函数的结果应如下所示:

[{
  "id": 3,
  "parent": 2,
  "name": "Grand Child 1"
}, {
  "id": 4,
  "parent": 2,
  "name": "Grand Child 2"
}]
Run Code Online (Sandbox Code Playgroud)

创建函数来解决这种情况的正确方法是什么?谢谢.

Mar*_*eis 5

您可以仅遍历原始数据并查找具有指定ID作为parent_id的项目。如果找到,则对元素的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)
Run Code Online (Sandbox Code Playgroud)

打印出来

Child 1
-> Grand Child 1
-> Grand Child 2
Child 2
Run Code Online (Sandbox Code Playgroud)