Jo Ko Jo Ko - 2 months ago 7
HTML Question

Inside an array, how to check for unique property and add an object to it in Javascript?

So I will be constantly retrieving an object with the following format:

student: {
"student_id": "12345",
"class_number": "abcd",
"location": "below",
}


and will be added to array with the following format:

students: [
{
"student_id": "",
"classes": []
},
]


So in Javascript, how can I add the
student
object to the
students
array based on the uniqueness of
student_id
and form an object with the class information, like
{"class_number": "", "location": ""}
, and add that to the array
"classes":[]
?

Example: Say I have three
student
objects:


student: {
"student_id": "12345",
"class_number": "abcd",
"location": "below",
}

student: {
"student_id": "12345",
"class_number": "efgh",
"location": "up",
}

student: {
"student_id": "67890",
"class_number": "abcd",
"location": "below",
}


And would like to add to the
students
array based on the uniqueness of the
student_id
and add relevant class information to the
classes
array, like so:

students: [
{
"student_id": "12345",
"classes": [
{
"class_number": "abcd",
"location": "below",
},
{
"class_number": "efgh",
"location": "up",
},
]
},
{
"student_id": "67890",
"classes": [
{
"class_number": "abcd",
"location": "below",
},
]
},
]


Thank you and will accept answer and upvote!

Answer

Something like this should do the trick:

var students = [];

function addStudent(student) {
  // Check if we already know about this student.
  var existingRecord = students.find(function (s) {
    return s.student_id === student.student_id;
  });

  var classInfo = {
    class_number: student.class_number,
    location: student.location
  };

  if (!existingRecord) {
    // This is the first record for this student so we construct
    // the complete record and add it.
    students.push({
      student_id: student.student_id,
      classes: [classInfo]
    });

    return;
  }

  // Add to the existing student's classes.
  existingRecord.classes.push(classInfo);
}

You would then invoke it as follows:

addStudent({
    "student_id": "67890",
    "class_number": "abcd",
    "location": "below",
});

Runnable JSBin example available here.

More available on Array.prototype.find at MDN.