rohanharikr
rohanharikr

Reputation: 1811

Changing the value of an array of objects based on another array in javascript

I have two arrays.

let arr1 = [{id: 1, favorite: false}, {id: 2, favorite: false}, {id: 3, favorite: false}];
let arr2 = [1, 3];

If the id exists in arr2, I want to change the favorite to true (of that particular object)

For example. in the above case, the final arr1 would look like

[{id: 1, favorite: true}, {id: 2, favorite: false}, {id: 3, favorite: true}];

Upvotes: 1

Views: 41

Answers (3)

Sameer
Sameer

Reputation: 5188

You can also use forEach and includes.

let arr1 = [{id: 1, favorite: false}, {id: 2, favorite: false}, {id: 3, favorite: false}];
let arr2 = [1, 3];

arr1.forEach(x => x.favorite = arr2.includes(x.id))

console.log(arr1);

Upvotes: 1

webcoder
webcoder

Reputation: 1517

You can also use some method like:

const newArr = arr1.map(item =>  { return { ...item, favorite: arr2.some(elem => elem === item.id) } })

Upvotes: 2

Majed Badawi
Majed Badawi

Reputation: 28414

You can use .map to iterate over arr1 and .includes to check if the item's id is in arr2:

const arr1 = [
  {id: 1, favorite: false}, 
  {id: 2, favorite: false}, 
  {id: 3, favorite: false}
];
const arr2 = [1, 3];

const res = arr1.map(e => 
  ({...e, favorite: arr2.includes(e.id)})
);

console.log(res);

Upvotes: 4

Related Questions