简体   繁体   English

为什么只有我的最后一个对象在对象中循环更新

[英]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. next 函数的目标是迭代 mapObject,如果 id 与值中的任何元素匹配,则将名为“on”的新属性设置为 true,否则将其设置为 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.将值更新为 true 后,您应该中断内部循环。

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] .问题是,一旦您将值更新为true您将再次使用相同的mapObject[i].id循环,并针对value[j]中的新值对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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