JavaScript更新多个对象属性

时间:2018-05-30 06:53:56

标签: javascript

我在下面的代码中使用findIndex方法和Update对象的name属性查找特定对象的索引。无论如何我可以更新多个对象的名称属性吗? E.g。

var rofl = ["0"]; 

//而不是[“0”]如何通过输入var rofl = [“1”,“2”,“3”]来更新多个对象;

let myArray = [
  {id: 0, name: "Jhon"},
  {id: 1, name: "Sara"},
  {id: 2, name: "Domnic"},
  {id: 3, name: "Bravo"}
],

objIndex = myArray.findIndex((obj => obj.id == rofl));

console.log("Before update: ", myArray[objIndex]) // {id: 0, name: "Jhon"}

myArray[objIndex].name = ("Jerry");

console.log("After update: ", myArray[objIndex]) // {id: 0, name: "Jerry"}

2 个答案:

答案 0 :(得分:3)

改为使用forEach



const myArray = [
  {id: 0, name: "Jhon"},
  {id: 1, name: "Sara"},
  {id: 2, name: "Domnic"},
  {id: 3, name: "Bravo"}
];
["1","2","3"].forEach(findId =>
  myArray.find(({ id }) => id == findId).name = 'Jerry'
);
console.log(myArray);




如果ID有可能在阵列中不存在,您也必须为此添加测试:



const myArray = [
  {id: 0, name: "Jhon"},
  {id: 1, name: "Sara"},
  {id: 2, name: "Domnic"},
  {id: 3, name: "Bravo"}
];
["1","2","3", "10"].forEach(findId => {
  const foundObj = myArray.find(({ id }) => id == findId);
  if (foundObj) foundObj.name = 'Jerry';
});
console.log(myArray);




答案 1 :(得分:2)

使用Array.forEach



let myArray = [{id: 0, name: "Jhon"},{id: 1, name: "Sara"},{id: 2, name: "Domnic"},{id: 3, name: "Bravo"}];
let rofl = ["1","2","3"];

myArray.forEach((obj) => {if(rofl.includes(obj.id.toString())) obj.name = 'Jerry'}) 

console.log(myArray);