Home > Net >  iterate and get values from nested arrays
iterate and get values from nested arrays

Time:05-14

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

CodePudding user response:

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);
}

  • Related