Tengo una lista profunda y un árbol en el que quiero cambiar todas las teclas de alternancia a verdaderas, pero, debido a la estructura, es difícil de lograr.
Escribí esta función pero es inútil. Necesito una con forEach y no funciona.
function loopThruAforest() { return state.data.map((tree) => { console.log(tree) && loopThruATree(tree) }); function loopThruATree(tree) { return tree.children.map((node) => { if (node.children !== null) { return console.log(tree) && loopThruATree(tree) } else { return node.datum; } }); } } { "data": [{ "datum": "String", "id": 1, "toggle": false, "children": [{ "datum": "String", "id": 2, "toggle": false, "children": [{ "datum": "String", "id": 3, "toggle": false, "children": [] }] }, { "datum": "String", "id": 4, "toggle": false, "children": [] } ] }, { "datum": "String", "id": 5, "toggle": false, "children": [{ "datum": "String", "id": 6, "children": [] }] } ]Puede intentar tener una variable to_visit para hacer un DFS:
function loopThruAforest(data){ let to_visit = [...data]; while(to_visit.length > 0){ let current = to_visit.pop() current.toggle = true; to_visit.concat( current.children) } }Puede usar Object.keys para iterar objetos y matrices. (Pero no olvide que no desea iterar cadenas).
function setTogglesTo(data, bool) { if (!data) return for (const key of Object.keys(data)) { if (key === "toggle") data[key] = bool if (typeof data[key] != "string") setTogglesTo(data[key], bool) } } setTogglesTo(dataObj, true) console.log(dataObj) <script> const dataObj = [{ "datum": "String", "id": 1, "toggle": false, "children": [{ "datum": "String", "id": 2, "toggle": false, "children": [{ "datum": "String", "id": 3, "toggle": false, "children": [] }] }, { "datum": "String", "id": 4, "toggle": false, "children": [] } ] }, { "datum": "String", "id": 5, "toggle": false, "children": [{ "datum": "String", "id": 6, "children": [] }] } ]; </script>