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

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

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 Report

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