Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!