Moxie C
Moxie C

Reputation: 442

Looping through array to get Key with Jquery

I would like to use Jquery to return the keys: Country, Country_Code and Continent and only have them showing up once.

 var countryList = [
          {"Country":"Canada","Country_Code":"CAN", "Continent":"North America"},
          {"Country":"USA","Country_Code":"USA","Continent":"North America"},
          {"Country":"Brazil","Country_Code":"BRA","Continent":"South America"},
          {"Country":"France","Country_Code":"FRA","Continent":"Europe"},
          {"Country":"Spain","Country_Code":"SPA","Continent":"Europe"}
 ];

How would I get return the actual key name without looping through the 5 objects Canada, USA, Brazil, France, and Spain in the countryList.

This is my code in jquery:

  $.each(countryList, function() {
     $.each(this, function(k, v) {
       console.log(k);
     });
  });

Thanks Cheers

Upvotes: 0

Views: 744

Answers (1)

clumsy
clumsy

Reputation: 716

I presume the language we are talking about here is JavaScript. In case all you want to get is the property name the below code should do, taking into consideration that all the objects in the array has the same set of them (otherwise you'll need to iterate them) just check the first one:

var result = []
for( var key in countryList[ 0 ] ) {
  result.push( key );
}
alert( result.join() )

Upvotes: 2

Related Questions