0

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?

1
  • Note that your var student = {}; assignment immediately gets invalidated by the student = classes[i].student; assignment. The result of those two lines if identical to running the single assignment var student = classes[i].student; Commented Oct 24, 2016 at 2:55

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

6 Comments

Actually I want to put student object to be the first level. If I use this code student: classes[i].student, it will be nested object.
I thought if I use `student = classes[i].student, it should refer to different object instead?
I've updated my answer with code that makes a copy of the classes[i].student object. Regarding your original student = classes[i].student, that assigns the student variable to refer to the same object that classes[i].student refers to.
Yeah many thanks for your help! But I thought for each classes[i].student will have different reference, thus I thought student = classes[i].student should be working..
No, for objects = makes another reference to the existing object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.