0

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

9
  • 1
    What language is this? You should add that as a part of the question and/or a tag. You should build a data structure that allows you access these directly instead of looping through them. Is there a reason this is an issue? Commented Jan 15, 2014 at 20:19
  • If you want to display the keys you just need to read the first array element and extract its keys. Commented Jan 15, 2014 at 20:34
  • (One presumes you've had enough sense to use an available kit to parse the JSON into objects in whatever language you're using.) Commented Jan 15, 2014 at 20:36
  • "without looping through the 5 objects" --- what is the technical requirement behind this limitation? Commented Jan 15, 2014 at 20:37
  • @Hot Licks: it actually is not a JSON, it's a JS array Commented Jan 15, 2014 at 20:38

1 Answer 1

2

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() )
Sign up to request clarification or add additional context in comments.

Comments

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.