![](/img/trans.png)
[英]Getting value of property of object inside an array inside another array
[英]Change object property of an object inside an array inside another array
實際上我已經做到了,但我相信你可以用 ES6 做到這一點。
不管你的邏輯,目標是在嵌套的 arrays 中找到一些 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;
}
}
}
非常感謝你。
在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..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.