Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
How to find and replace the value array item if condtion is true

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',
  },
 ] 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!