更改另一个数组内的一个数组内的对象的对象属性

时间:2020-05-01 04:52:26

标签: javascript ecmascript-6 vuex

实际上我已经完成了,但是我相信您可以使用ES6完成它。

无关紧要的逻辑是,目标是在嵌套数组中找到一些对象并更改数据(更改属性对象):

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

非常感谢您。

1 个答案:

答案 0 :(得分:1)

ES6类似。只是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)

与上述相同,但为good in performance。如果只有one match,则不会iterate所有数据。这将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);

演示:

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..