Tengo una matriz de objetos que se ve así:
[ { "text":"Same but with checkboxes", "opened": true, "children":[ { "text":"initially selected", "opened":true }, ] }, { "text":"Same but with checkboxes", "opened":true, "children":[ { "text":"initially open", "opened":true, "children":[ { "text":"Another node", "opened":true, } ] }, { "text":"custom icon", "opened":true, }, { "text":"disabled node", "opened":true, } ] }, { "text":"And wholerow selection", "opened":true, } ]Quiero saber si es posible cambiar el valor por ejemplo de la llave abierta (a falso) a todos los objetos en todos los niveles.. ¿cómo puedo hacer esto?
Intenté algo así sin éxito.
myArray.map(e => ({ ...e, opened: false }))Cree una función recursiva: si el objeto que se itera tiene una matriz de children , llámelo para todos esos niños.
const input=[{text:"Same but with checkboxes",opened:!0,children:[{text:"initially selected",opened:!0}]},{text:"Same but with checkboxes",opened:!0,children:[{text:"initially open",opened:!0,children:[{text:"Another node",opened:!0}]},{text:"custom icon",opened:!0},{text:"disabled node",opened:!0}]},{text:"And wholerow selection",opened:!0}]; const closeAll = (obj) => { obj.opened = false; obj.children?.forEach(closeAll); }; input.forEach(closeAll); console.log(input);La recursividad está aquí para ayudar. Busque recursivamente todos los objetos para la clave opened y cámbielo a falso.
var data = [ { "text": "Same but with checkboxes", "opened": true, "children": [ { "text": "initially selected", "opened": true }, ] }, { "text": "Same but with checkboxes", "opened": true, "children": [ { "text": "initially open", "opened": true, "children": [ { "text": "Another node", "opened": true, } ] }, { "text": "custom icon", "opened": true, }, { "text": "disabled node", "opened": true, } ] }, { "text": "And wholerow selection", "opened": true, } ]; function run(data) { for (let subData of data) { if (subData["opened"]) subData["opened"] = false; if (subData["children"]) run(subData["children"]) } } run(data) console.log(data)Simplemente extienda su método de mapa para manejar recursivamente. (los niños existen o no y Array u objeto único)
const updateOpened = (data) => { if (Array.isArray(data)) { return data.map(updateOpened); } const { children, ...item } = data; return children ? { ...updateOpened(item), children: updateOpened(children) } : { ...item, opened: true }; }; const arr=[{text:"Same but with checkboxes",opened:!0,children:[{text:"initially selected",opened:!0}]},{text:"Same but with checkboxes",opened:!0,children:[{text:"initially open",opened:!0,children:[{text:"Another node",opened:!0}]},{text:"custom icon",opened:!0},{text:"disabled node",opened:!0}]},{text:"And wholerow selection",opened:!0}]; console.log(updateOpened(arr));