Home > OS >  How to find and replace the value array item if condtion is true
How to find and replace the value array item if condtion is true

Time:04-27

I have an array like below

const arr = [
  {
    id: "first",
    val: 'ganguly',
  },
  {
    id: "third",
    val: 'sachin',
  },
 ]
 
 const selectedVaue ='dhoni';

if id is match to 'third' then value to replace to particular key

const list = arr.filter(data => data.id === 'third');
     if (list.length > 0 ) {
         // code 
     } 

Expected result lie below :

    const arr = [
  {
    id: "first",
    val: 'ganguly',
  },
  {
    id: "third",
    val: 'dhoni',
  },
 ] 

CodePudding user response:

You can use Array.prototype.map and create a new array with the value with id "third" replaced.

const arr = [
  { id: "first", val: "ganguly" },
  { id: "third", val: "sachin" },
];

const selectedValue = "dhoni";

const res = arr.map((a) =>
  a.id === "third" ? { ...a, val: selectedValue } : a
);

console.log(res);

Or you can use Array.prototype.forEach if you want to replace the object in place.

const arr = [
  { id: "first", val: "ganguly" },
  { id: "third", val: "sachin" },
];

const selectedValue = "dhoni";

arr.forEach((a, i) => {
  if (a.id === "third") {
    arr[i] = { ...a, val: selectedValue };
  }
});

console.log(arr);

  • Related