0

I have a fairly large JSON file and I wish to loop through certain keys with Jquery.

How would I use a variable ( "countrySelector" in the example below) in my $.each loop so I only filter through the relevant key/selector.

Here is my JSON layout

{ - world_projects: {
    - australia: {
        - {
            project_id: 123
          },
        - {
            project_id: 456
          },
    },
    - usa: {
        - {
            project_id: 789
          },
        - {
            project_id: 022
          },
    },
}

Here is my Jquery code:

jQuery(document).ready(function($) {

    // Grab the country
    var countrySelector = $( '#map-projects-wrapper' ).data('country');

    // Get our JSON file which contains all collections
    // and project information
    $.getJSON( "projects.json", function( jsonData ) {

        // Cycle through each Project
        $.each( jsonData.world_projects.countrySelector, function( project_key, projects ) {
            // here I would do my thing
        }
    }
});

I hope that makes sense,

Thank you Chris.

1 Answer 1

1

countrySelector is not a property, it is a variable holding the key name so you need to use bracket notation as the member operator

jsonData.world_projects[countrySelector]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Arun, that's perfect! :)

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.