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

Time:07-10

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,
}

CodePudding user response:

You can filter it out and change tha keys value. 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);

CodePudding user response:

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