Skip to content
Advertisement

How to iterate recursively over all children in nested objects

I am trying to iterate over all objects in my array and all children and for each I want to set the folded property to false

But I am getting an error:

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

Here is my array:

[
    {
        "id": 1,
        "title": "Title",
        "folded": true,
        "children": []
    },

    {
        "id": 2,
        "title": "Title",
        "folded": true,
        "children": [
            {
                "id": 3,
                "title": "Title",
                "folded": true,
                "children": []
            },

            {
                "id": 4,
                "title": "Title",
                "folded": true,
                "children": [
                    {
                        "id": 6,
                        "title": "Title",
                        "folded": true,
                        "children": []
                    }
                ]
            }
        ]
    },

    {
        "id": 5,
        "title": "Title",
        "folded": true,
        "children": []
    }
]

And here is my function

function selectActivePage(node) {
    for (let child of node.children) {
        child.$folded = false
        selectActivePage(child)
    }
}

selectActivePage(myArray)

Advertisement

Answer

You are passing child which is an object and that is not iterable, you have to pass it’s children. You can try checking if child having children array and then iterate children.

function selectActivePage(node) {
    for (let child of node) {
        child.folded = false;
        if(child.children && Array.isArray(child.children) && child.children.length > 0)
            selectActivePage(child.children)
    }
};
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement