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

401
Vistas
React.js - How to change object value inside array of objects

i have a problem with array of objects which is inside state. My question is how to change an object value like in example code bellow

const [theArrayOfObjects, setTheArrayOfObjects] = useState([
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "circle" }
    ]);

what i want is

[
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "rectangle" }
]

so in short i just want to update array of objects by changing only this specific value

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

0

setTheArrayOfObjects([
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "rectangle" }
  ]
)

While this might not be exactly what you asked it fits your needs and it is simple. Further complications like iterating through each element and finding pattern to reach specific element might end up with unexpected outputs.

If you don't like this, then you might come up with different state structure (an object instead of an array).

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a functional state update to correctly update from any previous state value. Shallow copy any parts of state that you are updating. Remember that the useState state updater function doesn't shallow merge your updates, you are returning an entire new state value.

Given:

const [theArrayOfObjects, setTheArrayOfObjects] = useState([
  { color: "blue", shape: "square" }, 
  { color: "red", shape: "circle" }
]);

Update as follows:

  • Map the previous array to a new array reference
  • Shallow copy the array element you want to update, appending the updated properties

Example:

const updateShape = (shape, index) => {
  setTheArrayOfObjects(state => state.map((el, i) => i === index
    ? { ...el, shape }
    : el,
   ));
};

...

updateShape("rectangle", 1);

Helpful

Even though it's from Redux, the Immutable Update Patterns documentation is incredibly helpful in explaining in more detail what I described above and is still applicable to standard React state updates. Please do a read though.

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