拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何使用JS从JSON格式中获取一个值

如何使用JS从JSON格式中获取一个值

白鹭 - 2022-01-26 2098 0 0

我只想使用 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 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *