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

179
Vistas
React - update object within object within array

Having trouble updating a field whose value if within an object within an object within an array:

      [
        { animals: { an1: 'lynx', an2: 'tiger' }, location: 'asia' },
        { animals: { an1: 'pigeon', an2: 'eagle' }, location: 'europe' },
      ];
const handleChange = (e, input) => {
    let updatedList = data.map((item, i) => {
        if (i === index) {
          const allAnimals = { ...item.animals };
          allAnimals[input] = e.target.value;

          return { ...item, animals: allAnimals }; 
        }
        return item;
      });
    
    setData(updatedList);

  }

How would I update an1 or an2 in the animals object?

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

0

If you simply would like to replace all indexes the following should work:

const data = [
  { animals: { an1: 'lynx', an2: 'tiger' }, location: 'asia' },
  { animals: { an1: 'pigeon', an2: 'eagle' }, location: 'europe' },
];

const handleChange = (e, input) =>
   data.map(it => ({
    ...it,
    animals: {
      ...it.animals,
      [input]: e.target.value,
    }
  }))

console.log(handleChange({
  target: {
    value: 'test',
  }},
  'an2'
))

Notice, that this will replace/add the new value to each array.

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