我想知道是否有办法从 .json
中获取“-temp”的每个值
{
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
}
我是如何尝试用 JavaScript 获取它的,但没有成功,我得到了 undefined
data.weather.notes.cities['-temp']
如何获取“-temp”的每个值?
最佳答案
您可以使用 map :
const temps = data.weather.notes.cities.map(city => city["-temp"]);
console.log(temps); // ["17", "16", "18"]
当然,您始终可以单独访问它们:
const { cities } = data.weather.notes;
console.log(cities[0]["-temp"]); // "17"
或者循环所有的:
for (let city of cities) {
console.log("temperature in %s is %s°",
city["-id"], city["-temp"]
);
}
关于javascript - 使用 json 从特定键中检索每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58858331/