[英]Retrieve each value from a specific key with json
我想知道是否有办法从.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"]
);
}
这是将城市的温度插入新数组的示例:
const newArray= new Array();
data.weather.notes.cities
.forEach(city => newArray.push(city['-temp']))
您可能会遍历所有城市并收集“-temp”键。
data.weather.notes.cities.forEach(function(element) {
for (var em in element) {
if (em == "-temp")
{
console.log(element[em])
}
}
});
@ZER0 答案可能是最好的。
var data = { "weather":{ "notes":{ "cities":[ { "-id":"scranton", "-temp":"17" }, { "-id":"paris", "-temp":"16" }, { "-id":"new york", "-temp":"18" } ] } } }; for(var i in data.weather.notes.cities) { let city = data.weather.notes.cities[i]; console.log(city["-temp"]); //You_ can get it here }
您不能像使用 jquery 选择器一样使用 JSON。 在您的情况下,您需要 map 您的城市阵列。
const object = {
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
};
const tempList = object.weather.notes.cities.map(city => city['-temp']);
//result: ["17", "16", "18"]
有关详细信息,请参阅map文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.