0

I have this JS object:

  baseFarm = {
    name: "Farm",
    tier: 1,
    gridPos: 32,
  }

and I want to push it to this array:

ownedLand = [];

This works perfectly, and if I console log this after the push I get: enter image description here

Now, I want to push another another object to the same array, using that one as a base, however, I want the "gridPos" property to be different:

var newLand = baseFarm;
newLand.gridPos = parseInt( $('#purchaseLandPopupPlotNum').text() );
this.ownedLand.push(newLand);

However, after pushing this new object, the old one gets updated too: enter image description here

What am I doing wrong?

Thanks in advance

Aaranihlus
  • 143
  • 2
  • 13

1 Answers1

1

You are assigning the same object to the new variable here:

var newLand = baseFarm;

So when you modify newLand, you are changing baseFarm aswell (and the object pushed to the array). And you are pushing the same object twice to the array.

Instead, you should clone baseFarm, either with Object.assign():

var newLand = Object.assign({}, baseFarm);

Or the more trendy spread operator:

var newLand = { ...baseFarm };

As an addendum, you could clone and modify the property on the same operation:

var newLand = Object.assign({}, baseFarm, { gridPos: parseInt( $('#purchaseLandPopupPlotNum').text() } );

In which case you wouldn't even need a new variable (or the baseFarm even, if it's always on the 0 index of the array):

this.ownedLand.push(Object.assign({}, this.ownedLand[0], { gridPos: parseInt( $('#purchaseLandPopupPlotNum').text() } ));

I'll let the spread version up to you :-)

Jcl
  • 27,696
  • 5
  • 61
  • 92