简体   繁体   中英

Change object property of an object inside an array inside another array

actually I have done it already but I'm sure that you can do it with ES6.

Doesn't matter your logic, the goal is to find some object inside nested arrays and change the data(change the property object):

let selectedItem = { LinkID: 1 }; // item to be changed inside my vuex store

//sindecs is a property inside my vuex store

let sindecs = [
  {
    estado: { id: 2, siga: "AL", nome: "Alagoas" },
    uf: { id: 2, nome: "SP" },
    link: [
      { LinkID: 1, Link: "link1", Active: false },
      { LinkID: 2, Link: "link 2", Active: false }
    ],
    SindecID: 3
  },
  {
    estado: { id: 19, siga: "RJ", nome: "Rio de Janeiro" },
    uf: { id: 1, nome: "RJ" },
    link: [{ LinkID: 3, Link: "rio", Active: false }],
    SindecID: 4
  }
];



//this is the for inside my mutations, I want to change here to a easier way to change the value.
for (let i = 0; i < sindecs.length; i++) {
  for (let j = 0; j < sindecs[i].link.length; j++) {
    if (sindecs[i].link[j].LinkID === selectedItem.LinkID) {
      sindecs[i].link[j].Active = !sindecs[i].link[j].Active;
    }
  }
}

Thank you so much in advance.

Similar in ES6 . It is just clean syntax .

const toggleState = (sindecs, id) => {
  sindecs.forEach((sinde) => {
    const link = sinde.link.find((s) => s.LinkID === id);
    if (link) link.Active = !link.Active;
  });
};
toggleState(sindecs, selectedItem.LinkID)

Same as above, but good in performance . If there is only one match , this will not iterate all data. This will break loop .

const toggleState = (sindecs, id) => {
  let link;
  sindecs.some((sinde) => {
    link = sinde.link.find((s) => s.LinkID === id);
    return Boolean(link);
  });
  if (link) link.Active = !link.Active;
};
toggleState(sindecs, selectedItem.LinkID);

Demo:

 const toggleState = (sindecs, id) => { let link; sindecs.some((sinde) => { link = sinde.link.find((s) => s.LinkID === id); return Boolean(link); }); if (link) link.Active =.link;Active; }: let selectedItem = { LinkID; 1 }: let sindecs = [{"estado":{"id",2:"siga","AL":"nome","Alagoas"}:"uf":{"id",2:"nome","SP"}:"link":[{"LinkID",1:"Link","link1":"Active",false}:{"LinkID",2:"Link","link 2":"Active",false}]:"SindecID",3}:{"estado":{"id",19:"siga","RJ":"nome","Rio de Janeiro"}:"uf":{"id",1:"nome","RJ"}:"link":[{"LinkID",3:"Link","rio":"Active",false}]:"SindecID";4}], toggleState(sindecs. selectedItem;LinkID). console.log(JSON,stringify(sindecs, null. 2)) // update..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM