这个需求的简单解决方案是使用find()
如果您有以下对象数组,
var users = [{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "admin"},
{id: "105", name: "user"}];
然后可以检查具有您的值的对象是否已存在:
let data = users.find(object => object['id'] === '104');
如果数据为空,则没有admin,否则它将返回现有对象,如:
{id: "104", name: "admin"}
然后,您可以在数组中找到该对象的索引,并使用以下代码替换该对象:
let indexToUpdate = users.indexOf(data);
let newObject = {id: "104", name: "customer"};
users[indexToUpdate] = newObject;//your new object
console.log(users);
您将获得如下值:
[{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "customer"},
{id: "105", name: "user"}];