简体   繁体   English

JavaScript更新多个对象属性

[英]JavaScript Update multiple object properties

I have this code below that finds the index of specific object using findIndex method and Update object's name property. 我下面的这段代码使用findIndex方法和Update对象的name属性来查找特定对象的索引。 Is there anyway i can update mutiple object's name property? 无论如何,我可以更新多个对象的name属性吗? Eg 例如

var rofl = ["0"]; 

// Instead of ["0"] how do i update multiple object by putting var rofl = ["1","2","3"]; //代替[“ 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"}

Use forEach instead: 使用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); 

If the IDs have a chance of not existing in the array, you'll have to add a test for that as well: 如果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); 

Use Array.forEach 使用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); 

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

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