Search code examples
javascriptarraysjsonjavascript-objects

Javascript: Looping through an object within an array


I have a JSON feed from which I need to extract some information to plot some markers onto a map. In order to do so I need to loop through the JSON feed, then loop through a particular object within the array.

I can get it to loop through the top level (category), but attempting to loop through each category is working as expected - I get the same cateogry repeated equal to the number categories.

The structure of the array/object is as so:

- activities
    |_ category
    |_ acf
        |_ activity_listing
            |_ name
            |_ latitude
            |_ longitude
            |_ name
            |_ latitude
            |_ longitude
    |_ category
    |_ acf
        |_ activity_listing
            |_ name
            |_ latitude
            |_ longitude
            |_ name
            |_ latitude
            |_ longitude

Each category has an activity listing with multiple items (name, lat, lng).

My code is setup as below:

var activitiesLocationList = this.activitiesLocations;

for (var i = 0; i < activitiesLocationList.length; i++) {

    activitiesLocationList[0]['acf']['activity_listing'].forEach(function(item) {

        var placeName = item['activity_listing-name'];
        var placeLatitude = parseFloat(item['activity-listing_latitude']);
        var placeLongitude = parseFloat(item['activity-listing_longitude']);

        console.log('Place Name: ' + placeName);

    })
}

The output is:

'Place Name: Karijini National Park'
'Place Name: Staircase to the Moon'
'Place Name: Millstream Chichester National Park'
'Place Name: Dampier Archipelago'
'Place Name: Murujuga National Park'
'Place Name: Montebello Islands'
'Place Name: Karijini National Park'
'Place Name: Staircase to the Moon'
'Place Name: Millstream Chichester National Park'
'Place Name: Dampier Archipelago'
'Place Name: Murujuga National Park'
'Place Name: Montebello Islands'

So it's almost doing what I want, but is only entering the first category. What am I doing wrong?

How do I get it to step through each category, looping the contents as it goes?


Solution

  • You are actually accessing 0th index only when you loop through object. replace activitiesLocationList[0]['acf']['activity_listing'] with activitiesLocationList[i]['acf']['activity_listing']. So your complete code will look like below

    var activitiesLocationList = this.activitiesLocations;
    
    for (var i = 0; i < activitiesLocationList.length; i++) {
    
        activitiesLocationList[i]['acf']['activity_listing'].forEach(function(item) {
    
            var placeName = item['activity_listing-name'];
            var placeLatitude = parseFloat(item['activity-listing_latitude']);
            var placeLongitude = parseFloat(item['activity-listing_longitude']);
    
            console.log('Place Name: ' + placeName);
    
        })
    }