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

163
Vistas
Update an element from one of multiple arrays

I have an object of 4 arrays like following

const data = {
  arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
  arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
  arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
  arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}

Then I need to find an element and update it. Here is what I tried:

const updateElement = (id: number, newName: string) => {
  let idx: number;

  idx = data.arr1.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr1[idx].name = newName;

  idx = data.arr2.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr2[idx].name = newName;

  idx = data.arr3.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr3[idx].name = newName;

  idx = data.arr4.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr4[idx].name = newName;
}

Is there any better way to update an element form multiple arrays than my approach? Suppose that every array has the same element interface.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you can use Object.values() and flat() array for update it :

const data = {
  arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
  arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
  arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
  arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}
const updateElement = (id, newName) => {
  const values = Object.values(data).flat().find(ele => ele.id === id)
  if(values) values.name = newName
}
updateElement(1, 'newName')
console.log(data)

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