Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda