'iterate and get values from nested arrays [closed]
In a array with unlimited nested array children it is necessary to get a list of parent and children values.
I need to iterate through an undetermined number of children (number which is not known at first) and get de values.
let data = [{
"id": 1,
"name": "parent 1"
"note": "note 1",
}, {
"id": 2,
"name": " parent 2",
"note": "note 2",
"children": [{
"id": 21,
"name": "child A of 2",
"note": "note A of 2",
},{
"id": 22,
"name": "child B of 2",
"note": "note B of 2",
},{
"id": 23,
"name": "child C of 2",
"note": "note C of 2",
"children": [{
"id": 231,
"name": "child A of 23",
"note": "note A of 23",
"children": [{
"id": 2311,
"name": "child A of 231",
"note": "note A of 231",
"children": []
}]
}]
}]
}]
Expected resul:
parent 1
note 1
parent 2
note 2
child A of 2
note A of 2
child B of 2
note B of 2
child C of 2
note C of 2
child A of 23
note A of 23
child A of 231
note A of 231
EDITED:
This is a small piece of something more complex. That's why I asked a question that seems too simplistic.
The objective is to collect the data resulting from a recursive query normally destined for a hierarchical tree, with each item in the tree having one-to-many relationships, therefore having associated collections, with undetermined nested collections, and transforming them (include the collections) into a simple list, removing all the hierarchy.
Solution 1:[1]
This is a good use case for a generator function, and yield*
for the recursive call:
function* iterData(data) {
for (const item of data) {
yield item;
if (item.children) yield* iterData(item.children);
}
}
// Demo
let data = [{"id": 1,"name": "parent 1","note": "note 1",}, {"id": 2,"name": " parent 2","note": "note 2","children": [{"id": 21,"name": "child A of 2","note": "note A of 2",},{"id": 22,"name": "child B of 2","note": "note B of 2",},{"id": 23,"name": "child C of 2","note": "note C of 2","children": [{"id": 231,"name": "child A of 23","note": "note A of 23","children": [{"id": 2311,"name": "child A of 231","note": "note A of 231","children": []}]}]}]}];
for (let {name, note} of iterData(data)) {
console.log(name);
console.log(note);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | trincot |