实际上我已经做到了,但我确信您可以使用 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;
}
}
}
提前非常感谢您。
最佳答案
与 ES6
类似。这只是干净的语法
。
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)
与上面相同,但是性能良好
。如果只有一个匹配
,则不会迭代
所有数据。这将打破循环
。
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..
关于javascript - 在另一个数组中更改数组内对象的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61536996/