Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda