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

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

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