I have a deep list and tree in which I want to change all the toggle keys to true, but, because of the structure it's hard to accomplish.
I wrote this function but it's useless I need one with forEach and it doesn't work
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": []
}]
}
]
You can try to have a to_visit variable to make a 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)
}
}
You can use Object.keys to iterate objects and arrays. (But don't forget that you don't want to iterate strings.)
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>