I'm having this problem in Javascript: I want to get the longitude and latitude values from an array of Objects. This all works fine, but when I try to save it into a global array, it overwrites every previous value. The result is an array with 8 times the last pushed 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 time asking a question here. So if I forgot something, please say so.
You could try to declare and instantiate the mark
object inside the for
loop because right now you are modifying the same instance all the time:
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);
}
The problem is that you are repeatedly modifying the same object. Your array ends up containing eight references to that one object.
To fix, move
mark = {};
into the for
loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With