简体   繁体   中英

Why is only my last object being updated in loop in object

I have two objects, One is an array that looks like this:

let value = [123,500];

The other is an array of objects that looks like this:

let mapObject = [
  {id:123,name:"Thing 1"},
  {id:444,name:"Thing 2"},
  {id:500,name:"Thing 3"},
  {id:777,name:"Thing 4"}
];

The goal of the next function is to iterate over the mapObject and if the id matches any of the elements in the value, then set a new property called 'on' to true, otherwise set it to false. Here is the code for that:

for (let i in mapObject) {
  for (let j in value) {
    if (mapObject[i].id == value[j]) {
      mapObject[i].on = true;
    } else {
      mapObject[i].on = false;
    }
  }
}

What I expect is this:

[
  {id:123,name:"Thing 1",on:true},
  {id:444,name:"Thing 2",on:false},
  {id:500,name:"Thing 3",on:true},
  {id:777,name:"Thing 4",on:false}
]

However what I am actually getting it this:

[
  {id:123,name:"Thing 1",on:false},
  {id:444,name:"Thing 2",on:false},
  {id:500,name:"Thing 3",on:true},
  {id:777,name:"Thing 4",on:false}
]

Why does this happen?

Your loop logic is not good. Once you update the value to true you should break from the inner loop.

for (let i in mapObject) {
    for (let j in value) {
        if (mapObject[i].id == value[j]) {
            mapObject[i].on = true;
            break;
        } else {
            mapObject[i].on = false;
        }
    }
}

The problem is that once you update the value to true you loop again with the same mapObject[i].id and test it against a new value from value[j] .

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