Riaan
Riaan

Reputation: 195

Iterating over an array of objects?

Here is some sample data that I get from an API:

{
  "Document": {
    "Placemark": [
      {
        "name": " V5-MJW",
        "address": "Aviation Road, Windhoek, Namibia",
        "description": [],
        "TimeStamp": {
          "when": "2016-05-21T06:12:00-04:00"
        },
        "styleUrl": "#asset7541",
        "Point": {
          "coordinates": "17.0829055,-22.598271,743"
         }
      },
      {
        "name": "GSatMicro80149",
        "address": "Unnamed Road, Lesotho",
        "description": [],
        "TimeStamp": {
          "when": "2016-05-11T04:52:00-04:00"
        },
        "styleUrl": "#asset7543",
        "Point": {
          "coordinates": "27.5594894,-29.456703,1659"
         }
      }
    ]
  }
}

This is my current code that is creating an array:

var flightPlanCoordinates = [];

//data being the returned values from the API.
$.each(data.Document.Placemark, function () {

    var location = this.Point.coordinates.split(',');
    var loc = {lat: parseFloat(location[1]), lng: parseFloat(location[0])};

    flightPlanCoordinates[this.name] == null ? flightPlanCoordinates[this.name] = [] : flightPlanCoordinates[this.name].push(loc);
});

I get a lot of placemarks with the same name, I want to split each placemark with a different name into a different array.

This all works fine until I try to itterate over flightPlanCoordinates, I tried the following:

$.each(flightPlanCoordinates, function(index) { 

}

But this does not work, If I log the length of flightPlanCoordinates, it results in 0, yet in Firefox Dev tools I can see the correct values inside of flightPlanCoordinates.

How would I go about doing this? Is there a better way than what I am doing here?

Upvotes: 1

Views: 74

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386600

Please change

var flightPlanCoordinates = [];

to

var flightPlanCoordinates = {};

it should be an object, because you set it with properties like flightPlanCoordinates[this.name], where this.name is a string, not an index.

Upvotes: 2

Related Questions