Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get one value from JSON format using JS

I would like to get only one data type from a JSON file using JS.
the field that I want to get is "name".
the JSON format is:

{"countries":
 {"country":[
  {"id":"1","name":"Europe","active":"on","dir":"yes"}, 
  {"id":"2","name":"Africa","active":"on","dir":"yes"},
  {"id":"3","name":"North America","active":"on","dir":"yes"}, 
 ]}
}

the require result is:
Europe
Africa
North America

Thanks for the help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This has nothing to do with JSON. Your code represents a (javascript) Object literal/initializer.

From that Object you can map the name property of each entry of the nested array from countries.country.

const myObj = { "countries":
 {"country":[
  {"id":"1","name":"Europe","active":"on","dir":"yes"}, 
  {"id":"2","name":"Africa","active":"on","dir":"yes"},
  {"id":"3","name":"North America","active":"on","dir":"yes"}, 
 ]}
};

const countryNames = myObj.countries.country.map( c => c.name );

console.log(countryNames);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading