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

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

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

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 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