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

137
Visualizações
How to update an item in an array of an object

I have a list of people, each with an id. I have to add a tag to a newly created array for a person with a certain id. The json object 'students' already exists and I am updating it using its useState setStudents method but it seems to be returning an unidentified object back. My plan was as follows:

  1. Map through the previousStudents
  2. If the id matches (the person who I'm adding a tag to), then add the tag. The if statement to add a tag is there because the 'tags' property doesn't initially exist, so I make it on the first tag add
  3. If the id doesn't match, just return that student
const updateStudent = (tag, id) => {
    setStudents((prevStudents) => {
      prevStudents.map((student) => {
        if (student.id !== id) return student;
        if (student.tags) {
          student["tags"].push(tag);
        } else {
          student["tags"] = [tag];
        }
        return student;
      });
    });
};

Sorry if my explanation was confusing but tldr: I'm just trying to add an item to an array of a specified object and it doesn't seem to be working.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A "cleaner" approach would be something like this:

const updateStudent = (tag, id) => {

  // form a new students object
  let newStudents = students.map(student => {
    if(student.id === id) {
      student.tags? student.tags.push(tag) : student.tags = [tag];
    }
    return student;
  });

  setStudents(newStudents); // set the newly formed object to state
}

It is better to separate the update logic from setting the 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