7

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.

2
  • What do you want the global and local variables to be, here? currently, mark is global, _coordinates is assumed + global, _data is assumed + global. Commented Aug 21, 2013 at 15:35
  • so problem is you are working on the same instance of mark Commented Aug 21, 2013 at 15:35

3 Answers 3

6

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

@OttoAllmendinger, are you sure? Did you test it? Because this seems to work perfectly fine: jsfiddle.net/bGGPX Why would this demo work if you were right?
@OttoAllmendinger The var declaration is indeed hoisted, but because mark is still being reassigned to a new object every loop, this still works.
Whoops, you're right. Been bitten to often by it, now I'm too paranoid ;-)
2

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.

Comments

1

You are mutating the (global) variable mark in every loop. Do this instead

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.