JAVASCRIPT: Change the key pair in a list of objects where the object ID matches

Viewed 21

I have an object as follows

{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":false,
}

My question is, what JavaScript is required to change the 'favorite' value ONLY where the id = 34567

So the result will become ;

{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":true,
}
2 Answers

You can filter it out from the array, and change the keys value of the first elemnt of the array of filtered elements. Like here:

const data = [{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":false,
}];

console.log(data);

const addFavorite = (id) => {
  data.filter((d) => d.id==id)[0].favorite = true;
}

addFavorite(34569);
console.log(data);

Or you can use the find method if tha ID's are unique, as
@cmgchess mentioned below in the comments section.

const data = [{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":false,
}];

console.log(data);

const addFavorite = (id) => {
  data.find((d) => d.id==id).favorite = true;
}

addFavorite(34569);
console.log(data);

And you can map through all the filtered elements if the ID isn't unique.

const data = [{
  "id":34567,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"The description goes here",
  "favorite":false,
},
{
  "id":34569,
  "description":"It is a copy",
  "favorite":false,
}
];

console.log(data);

const toggleFavorite = (id) => {
  data.filter((d) => d.id==id).map((d)=>d.favorite = !d.favorite);
}

toggleFavorite(34569);
console.log(data);

you can use map function for this.

data = data.map(d => {
    if(d.id === 34569) {
        d.favorite = true;
    }
    return d;
});

this will also work if there are multiple objects in array which satisfy the condition.

Related