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

169
Visualizações
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 Respostas
Responde à pergunta

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