Home > Back-end >  How to update an item in an array of an object
How to update an item in an array of an object

Time:02-13

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.

CodePudding user response:

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

  • Related