简体   繁体   English

查找和更新数组中的对象

[英]Find and update an object in an array

I want to get an object from an array of objects, then update it. 我想从对象数组中获取一个对象,然后对其进行更新。

var myObjs = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];

var myObjectToUpdate = _.findWhere(myObjs, { id: 2 });

myObjectToUpdate = { id: 2, name: "boop" };

myObjs[1] // { id: 2, name: "boop" }

Currently when I update myObject in the 3rd line, it does not update the array of objects. 当前,当我在第三行更新myObject时,它不会更新对象数组。 I'm assuming it is updating the new variable instead of referencing. 我假设它正在更新新变量而不是引用。

What is the correct way to do this? 正确的方法是什么?

@E_net4 is correct, you are reassigning the object you just found. @ E_net4是正确的,您正在重新分配刚刚找到的对象。

If all you need to do is update the name, try this: 如果您需要做的就是更新名称,请尝试以下操作:

var myObjs = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];

var myObjectToUpdate = _.findWhere(myObjs, { id: 2 });

myObjectToUpdate.name = "boop";

myObjs[1] // { id: 2, name: "boop" }

I guess this is what you want. 我想这就是你想要的。 You have, in your code, misconceptions. 您的代码中存在误解。 Please read my code and compare both. 请阅读我的代码并进行比较。

Hope it helps! 希望能帮助到你!

function fn(arr, toReplace, newValue) {
  for(var x in arr) {
    for(var k in toReplace) {
      if(arr[x][k] == toReplace[k]) {
        arr[x] = newValue;
      }
    }
  }
  return arr;
};

var arr = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var newValue = {id: 2, name: "boop"};

arr = fn(arr, {id: 2}, newValue);
console.log(arr);

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

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