-3

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)
martins16321
  • 591
  • 1
  • 5
  • 15
  • 1
    you need to add `if(node && node.children)` to check for undefined – Liam Apr 11 '22 at 13:38
  • The array doesn't have a "children" property. The recursive function should take an array and iterate over it. – Dave Newton Apr 11 '22 at 13:39
  • Does this answer your question? [Traverse all the Nodes of a JSON Object Tree with JavaScript](https://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript) – Jorge Guerreiro Apr 11 '22 at 13:46
  • You're passing in an array and it expects a node. – James Apr 11 '22 at 13:51

1 Answers1

2

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)
    }
};
MORÈ
  • 2,480
  • 3
  • 16
  • 23