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

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

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 Relatório

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