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

120
Visualizações
How to simultaneously update multiple object's values inside an array

I'm trying to simultaneously update 2 object's values inside an array when an onClick function is called. Currently I am able to decrement the target (selected) value by 1 (e.g -1) but am in need of suggestions for my next expectation:

If a previous value exists (e.g an option is selected) and I select a different option (radio button) I expect the previous value to increment by 1 (+1) simultaneously to the new value being decremented.

Array Structure:

`(4) [{…}, {…}, {…}, {…}]
0: {name: 'Space pod', total_no: 2, max_distance: 200, speed: 2}
1: {name: 'Space rocket', total_no: 1, max_distance: 300, speed: 4}
2: {name: 'Space shuttle', total_no: 1, max_distance: 400, speed: 5}
3: {name: 'Space ship', total_no: 2, max_distance: 600, speed: 10}`

Current:

const handleVehiceChange = (e) => {
setValue(e.target.value);
setVehiclesData(
  vehiclesData.map((vehicle) =>
    vehicle.name === e.target.value
      ? { ...vehicle, total_no: vehicle.total_no - 1 }
      : vehicle
  )
)};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Rather than overwriting the previous state with new state with a decremented total_no, I'd have a function that calculates the decremented result without putting the result into state. This makes it easy to switch between selected names to decrement.

const handleVehiceChange = (e) => {
  setValue(e.target.value);
};
const makeMergedData = () => vehiclesData.map((vehicle) =>
  vehicle.name === value // from state
    ? { ...vehicle, total_no: vehicle.total_no - 1 }
    : vehicle
);

Then replace consumers of vehiclesData with makeMergedData().

If the vehiclesData isn't being changed anywhere else, this might let you remove it from state completely.

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