Home > Mobile >  How to get one value from JSON format using JS
How to get one value from JSON format using JS

Time:01-03

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

CodePudding user response:

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);

CodePudding user response:

const countryNames = []
data.countries.country.forEach(item => {
     countryNames.push(item.name)
})

console.log(countryNames)

CodePudding user response:

const data = {"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"}, 
 ]}
}

console.log(
  data.countries.country.map(country => country.name)
)

CodePudding user response:

You can loop through, using

// parse it first
let data = JSON.parse( /* your file */);
let arr = [];
for (country in data.countries) {
    for (name in country) {
        arr.push(name)
    }
}
console.log(name);
// Expected result: ['Europe','Africa','North America']
  • Related