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

114
Visualizações
How to use setState to update the property of an object inside an array the right way in class component?

I have an array of objects in the state with the following structure:

const arrayOfTests = [
    {
        id: 1,
        name: "test1",
        description: "test description"
    },
    {
        id: 2,
        name: "test2",
        description: "test description"
    },
    {
        id: 3,
        name: "test3",
        description: "test description"
    }
]

Lets say I find object with id of 3 like this:

let object3 = arrayOfTests.find((element) => {
    return element.id === 3;
})

And then I edit it like this:

object3.description = "new description"

I'm kinda confused how to use setState to replace/edit the old object 3, with the new updated one.

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

0

Use the map() method as shown below.

Inside the callback function, check if the condition element.id === 3 is true; if it is, return a new object. Otherwise, return the current element as it is.

let newState = arrayOfTests.map((element) => {
    if (element.id === 3) {
       return { ...element, description: "new description" };
    }
   
    return element;
});

Pass the array returned by the map() method to the state setter function.

this.setState({ state: newState });
about 4 years ago · Juan Pablo Isaza Relatório

0

setState((prevState) => ({
  ...prevState,
  arrayOfTests: prevState.arrayOfTests.map((item) =>
    item.id === 3 ? { ...item, description: "new description" } : item
  ),
}));
about 4 years ago · Juan Pablo Isaza Relatório

0

this.setState({
  arrayOfTests: arrayOfTests.map(item => {
    if (item.id === 3) {
      return {
        ...item,
        description: 'new description'
      }
    }
    return item
  })
})
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