SakoBu SakoBu - 1 month ago 7
Ajax Question

Drilling through json data

I have this API https://api.nasa.gov/neo/rest/v1/feed?start_date=2015-09-07&end_date=2015-09-08&detailed=false&api_key=DEMO_KEY

I'm having trouble drilling down to the data:

How can I get it to give me only the data where is_potentially_hazardous_asteroid": true? Using jQuery Ajax and it is giving me undefined...

$(document).ready (function () {
var url = "https://api.nasa.gov/neo/rest/v1/feed?start_date=2015-09-07&end_date=2015-09-08&api_key=DEMO_KEY";
$.ajax({
url: url,
success: function(data){
console.log(data.near_earth_objects.2015-09-08);
}
});
});

Answer

Try this instead:

$(document).ready (function () {
    var url = "https://api.nasa.gov/neo/rest/v1/feed?start_date=2015-09-07&end_date=2015-09-08&api_key=DEMO_KEY";
    $.ajax({
        url: url,
        success: function (data) {
            // you can't use dot syntax with numbers:
            // console.log (thing.123);
            // try this instead:
            var neos = data.near_earth_objects['2015-09-08'];
            // and to find the hazardous asteroids:
            var hazardous_neos = neos.filter (function (d) {
                // return true to add d to the array returned from filter()
                // return false to NOT add d to the array from filter()

                // if we want hazardous asteroids then
                // since is_potentially_hazardous_asteroid is a
                // boolean where true means it's hazardous then
                // we can simply return its value
                return d.is_potentially_hazardous_asteroid;

                // if we want NON-hazardous asteroids we can do:
                //return d.is_potentially_hazardous_asteroid == false;
            });

            console.log (hazardous_neos);
        }
    });
});
Comments