Rendy Rendy - 1 month ago 7
Javascript Question

Array push still using previous reference?

I have following code:

var students = [];
for(var i = 0; i < classes.length; i++) {
var student = {};
student = classes[i].student;
student.teacher = classes[i].teacher;
students.push(student);
}


Somehow the students will print same object for all its contents, although I have put
var student = {};
inside the loop, thus it must not refer to same reference.

Anyone has idea why this happens?

Answer

You put student = {} inside the loop, then on the line immediately following that one you overwrote that by assigning student = classes[i].student.

If the intention is to make a copy of whatever classes[i].student is you can use the Object.assign() method:

var student = Object.assign({}, classes[i].student);

In context:

var students = [];
for(var i = 0; i < classes.length; i++) {
    var student = Object.assign({}, classes[i].student);
    student.teacher = classes[i].teacher;
    students.push(student);
}

(Note that Object.assign() doesn't do a deep copy - I'm not sure if that matters because you haven't shown what the classes array structure is.)

You could also use the .map() method instead of an explicit for loop:

var students = classes.map(function(c) {
  var student = Object.assign({}, c.student);
  student.teacher = c.teacher;
  return student;
});
Comments