Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript push Object to global array overwrites previous values?

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.

like image 555
Sylvareth Avatar asked Aug 21 '13 15:08

Sylvareth


2 Answers

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);
}
like image 112
Darin Dimitrov Avatar answered Sep 19 '22 21:09

Darin Dimitrov


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.

like image 42
NPE Avatar answered Sep 17 '22 21:09

NPE