Hidayat Hidayat - 1 month ago 6
JSON Question

Get all children from parent child JSON data

I have parent-child JSON data and I want get all children (nested children) from selected parent.

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"
}]


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"
}]


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.

Answer

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.

Check it out here: 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)

prints out

Child 1
-> Grand Child 1
-> Grand Child 2
Child 2