我只想使用 JS 从 JSON 档案中获取一种资料型别。
我想得到的栏位是“名称”。
JSON 格式为:
{"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"},
]}
}
要求的结果是:
欧洲
非洲
北美
谢谢您的帮助
uj5u.com热心网友回复:
这与 JSON 无关。您的代码代表一个(javascript) Object literal/initializer。
从该物件,您可以从 .map 映射嵌套阵列的每个条目的 name 属性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);
uj5u.com热心网友回复:
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)
)
uj5u.com热心网友回复:
您可以回圈使用
// 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']
uj5u.com热心网友回复:
let data= JSON.parse(yourJson);
data.countries.country.forEach((item) => {
console.log(item.name);
});
uj5u.com热心网友回复:
let countryNames = data.countries.country.filter(item => item.name !== '')
或者
const countryNames = []
data.countries.country.forEach(item => {
countryNames.push(item.name)
})
console.log(countryNames)
uj5u.com热心网友回复:
接受的答案比我省了一步 - 注意,谢谢。
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);
回传名称阵列 ['Europe', 'Africa', 'North America']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
0 评论