Black
Black

Reputation: 20372

Array of objects contains same object over and over again

I create multiple objects and push them to the array objArr:

var objArr = [];
var obj = {};
var height = [9,8,7,3,6,5,2,4];

for (var i = 0; i < 8; i++) {
debugger;
  var mountainH = height[i];

  obj.h = mountainH;
  obj.index = i;

  objArr.push(obj);
}

for (var i = 0; i < objArr.length; i++) {

  alert(objArr[i].h);
}

But as you can see, each object has the same values. Why?

enter image description here

Upvotes: 0

Views: 604

Answers (3)

user9274775
user9274775

Reputation:

As noted, you need to initialize a new object in each iteration of the loop, otherwise all your array members simply share the same object reference.

Additionally, your code can be greatly reduced by building the array using .map(), and fully using the object literal initializer to declare the properties.

var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((n, i) => ({h: n, index: i}));

console.log(objArr);

This is shorter and clearer. For every number in height, it creates a new object and adds it to a new array, which is returned from .map().


It can be even a little shorter with the newer features for object literals.

var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((h, index) => ({h, index}));

console.log(objArr);

Upvotes: 1

Ele
Ele

Reputation: 33736

  • Put the initialization of obj within your for-loop.

You were re-assigning new values to a global variable obj.

var objArr = [];

var height = [9,8,7,3,6,5,2,4];

for (var i = 0; i < 8; i++) {
debugger;
  var obj = {};
  var mountainH = height[i];

  obj.h = mountainH;
  obj.index = i;

  objArr.push(obj);
}

for (var i = 0; i < objArr.length; i++) {

  console.log(objArr[i].h);
}

Upvotes: 4

void
void

Reputation: 36703

Because the scope of obj in your code is global and it should rather be contained in the for loop.

If you will not declare it inside the loop then the value will get overwritten of the same obj on each iteration instead of a new memory allocation.

var objArr = [];
var height = [9, 8, 7, 3, 6, 5, 2, 4];

for (var i = 0; i < 8; i++) {
  debugger;
  var mountainH = height[i];
  var obj = {};

  obj.h = mountainH;
  obj.index = i;

  objArr.push(obj);
}
console.log(obj);

Upvotes: 3

Related Questions