2

I have this code below that finds the index of specific object using findIndex method and Update object's name property. Is there anyway i can update mutiple object's name property? E.g.

var rofl = ["0"]; 

// Instead of ["0"] how do i update multiple object by putting 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 Answers 2

3

Use forEach instead:

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:

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);

Sign up to request clarification or add additional context in comments.

Comments

2

Use 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.