Home > Net >  change value of a key in all objects of an array JAVASCRIPT
change value of a key in all objects of an array JAVASCRIPT

Time:12-16

I have an array of objects that looks like this:

[
   {
        "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,
    }
]

I want to know if it is possible to change the value for example of the key opened (to false) to all objects at all levels .. how can I do this?

I tried something like that without success

myArray.map(e => ({ ...e, opened: false }))

CodePudding user response:

Make a recursive function - if the object being iterated over has a children array, call it for all such children.

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);

CodePudding user response:

Recursion is here to help. Recursively search all the objects for opened key and switch it to false.

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)

  • Related