Home API - Isolating returned JSON keys and values within indexed objects
Reply: 2

API - Isolating returned JSON keys and values within indexed objects

maxineheadroom Published in 2017-12-07 21:39:18Z

Building a web app using a flight data API and, welp, the struggle is real.

My returned array and it's objects look something like this:


0:{destination: "YTO", 
departure_date: "2018-01-24", 
return_date: "2018-01-25"
airline: "TS"}

1:{destination: "BOS", 
departure_date: "2018-01-08", 
return_date: "2018-01-11",
airline: "AC"}

2:{destination: "SJU", 
departure_date: "2018-01-31", 
return_date: "2018-02-01", 
airline: "AA"}

Before I can dump the results into the DOM to display them to the visitor of the site, I need to run certain returned values through an additional API (long story) so I obviously need to isolate them somehow.

For this example, I'm using destination so my initial thought process is start by to logging out:


Which we know will print the FIRST destination in the FIRST object, since [0] is the index of that object (so in this case in this case we get back YTO).

Since every returned object has an index number, I think I need to loop through them (for each?) to pull the values I need but I'm trying variations of that with no luck.....or for all I know it's something else entirely.

(your two cents goes here)

Brian Peacock
Brian Peacock Reply to 2017-12-07 22:03:56Z

You can turn an Object's keys into an array with the Object.keys() method, this will allow you to use the Array.forEach() method to loop through an Object's enumerable properties, like so...

Object.keys(dataObj).forEach(function(k) {
    var dest = dataObj[k].destination;
    /* ... etc ... */

Hope that helps.

  • More on Object.keys() @MDN
Amit Wagner
Amit Wagner Reply to 2017-12-07 21:43:10Z

forEach works for arrays. try using for loop

for(let key in response.results){

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301571 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO