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

118
Visualizações
Update react State array of nested objects

Maybe this is stupid but my state is an array of nested objects :o It looks as follows:

  const data = [
        {
            randomid1: {
                name: 'lorem',
                latinName: 'ipsem',
            },
        },
        {
            randomid2: {
                name: 'lorem2',
                latinName: 'ipsem2',
            },
        },
    ]

I need to update this array with a new name and/or latinName for one of the items (let's say randomid1.name .

I have been struggling with spreading etc but keep getting errors. Now im trying mapping over something but this too won't work. Anyone?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can check if the array contains a certain item using Array#find and Object#hasOwnProperty:

const 
  data = [
    { randomid1: { name: 'lorem', latinName: 'ipsem' } },
    { randomid2: { name: 'lorem2', latinName: 'ipsem2' } }
  ],
  id = 'randomid2';

const elem = data.find(e => e.hasOwnProperty(id));
if(elem) {
  elem[id].name = 'new name';
}

console.log(data);

about 4 years ago · Juan Pablo Isaza Relatório

0

I think that the solution already provided is better but if you would like to know how it could be possible with map, here is one way doing it :

const data = [
  { randomid1: { name: 'lorem', latinName: 'ipsem' } },
  { randomid2: { name: 'lorem2', latinName: 'ipsem2' } }
];

const id = 'randomid2';

const newdata2 = data.map((elt) => {
  if (elt[id]) {
    return {[id] : {...elt[id], name: "new Name"}};
  }
 return elt;
});

console.log(newdata2)

about 4 years ago · Juan Pablo Isaza Relatório

0

I would do this :

// will iterate on all the top level objects
for (const itemWrapper of data) {
  // will iterate just once
  for (const item of Object.values(itemWrapper)) {
    if (item.name = 'whatever') {
      // update item
    }
  }
}

You can move this function and return when the item has been found for better performance.

PS : the data structure seems a bit hard to use, if you can change it to something that's indexed by what you're searching on, that would be great.

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