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
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);
Accepted answer saves a step from mine - noted, thanks.
let obj = {"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"},
]}
}
let objArray = obj.countries.country;
let names = objArray.map(item => item['name']);
console.log(names);
Returns an array of names ['Europe', 'Africa', 'North America']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
let countryNames = data.countries.country.filter(item => item.name !== '')
OR
const countryNames = []
data.countries.country.forEach(item => {
countryNames.push(item.name)
})
console.log(countryNames)