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

166
Views
How to add a field to an array of objects using useState in react

I'm building an app in react native and I want a way in which I can regularly add a field to one ore all of the user data before pushing it to the database, It is an array of objects and I know the index of each object. I'm aware of object destructuring but I don't know how to go about this. In the example below, how do I add the field "hobby" and a value of "Football" to smith alone? Thanks in advance.

const [usersData, setUsersData] = useState([
  {
    name: "Jane",
    sex: "female",
    age: "20",
  },
  {
    name: "Doe",
    sex: "male",
    age: "29",
  },
  {
    name: "Smith",
    sex: "male",
    age: "24",
  },
]);

const addHobby = (index, hobby) => {
  //Adding the field here//
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here's a way to achieve this:

const addHobby = (index, hobby) => {
  let temp = [...usersData] // Create a copy with the spread operator
  temp[index].hobby = hobby // Set new field
  setUsersData(temp) // Save the copy to state
}

...

addHobby(2, "Football") // 2 being known index of "Smith"

Edit: As suggested by @EmileBergeron, the spread operator creates a shallow copy only, which means the original state will still be mutated in case of object property changes. A more react friendly approach would be to use .map()

const addHobby = (index, hobby) => {

  // Create a copy using .map()
  const temp = usersData.map((data, idx) => {
    let tempData = {...data} // Copy object
    if(idx === index) tempData.hobby = hobby // Set new field
    return tempData
  }) 
  
  setUsersData(temp) // Save the copy to state
}
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!