Javascript push Object for global array overwrites previous values?

I have this problem in Javascript: I want to get the longitude and latitude values ​​from an array of objects. This all works great, but when I try to store it in a global array, it overwrites every previous value. The result is an array with the 8x last clicked object.

Global array: var _coordinates = [];

 function getCoordinates() { mark = {}; for(var key in _data) { if(_data.hasOwnProperty(key)){ mark["lng"] = _data[key].long; mark["lat"] = _data[key].lat; } console.log(mark); // Returns different coordinates (yay) _coordinates.push(mark); } console.log(_coordinates); // All coordinates are the same (meh) } 

This is my first question asking a question here. Therefore, if I forgot something, say so.

+6
source share
3 answers

You can try to declare and instantiate the mark object inside the for loop, because now you are constantly changing the same instance:

 function getCoordinates() { for(var key in _data) { var mark = {}; if(_data.hasOwnProperty(key)) { mark["lng"] = _data[key].long; mark["lat"] = _data[key].lat; } _coordinates.push(mark); } console.log(_coordinates); } 
+4
source

The problem is that you repeatedly modify the same object. Your array ends up with eight references to this one object.

To fix, move

 mark = {}; 

into the for loop.

+2
source

You mutate the (global) variable mark in each loop. Do it instead

 _coordinates.push({lng: _data[key].long, lat: data[key].lat}); 
+1
source

Source: https://habr.com/ru/post/952217/


All Articles