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

115
Views
How to use setState to update the property of an object inside an array the right way in class component?

I have an array of objects in the state with the following structure:

const arrayOfTests = [
    {
        id: 1,
        name: "test1",
        description: "test description"
    },
    {
        id: 2,
        name: "test2",
        description: "test description"
    },
    {
        id: 3,
        name: "test3",
        description: "test description"
    }
]

Lets say I find object with id of 3 like this:

let object3 = arrayOfTests.find((element) => {
    return element.id === 3;
})

And then I edit it like this:

object3.description = "new description"

I'm kinda confused how to use setState to replace/edit the old object 3, with the new updated one.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use the map() method as shown below.

Inside the callback function, check if the condition element.id === 3 is true; if it is, return a new object. Otherwise, return the current element as it is.

let newState = arrayOfTests.map((element) => {
    if (element.id === 3) {
       return { ...element, description: "new description" };
    }
   
    return element;
});

Pass the array returned by the map() method to the state setter function.

this.setState({ state: newState });
about 4 years ago · Juan Pablo Isaza Report

0

setState((prevState) => ({
  ...prevState,
  arrayOfTests: prevState.arrayOfTests.map((item) =>
    item.id === 3 ? { ...item, description: "new description" } : item
  ),
}));
about 4 years ago · Juan Pablo Isaza Report

0

this.setState({
  arrayOfTests: arrayOfTests.map(item => {
    if (item.id === 3) {
      return {
        ...item,
        description: 'new description'
      }
    }
    return item
  })
})
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!