[英]Retrieve each value from a specific key with json
I would like to know if there is a way to get every values of "-temp" from the .json
我想知道是否有办法从.json
中获取“-temp”的每个值
{
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
}
How I tried to get it with JavaScript but that didn't work and I get undefined
我如何尝试使用 JavaScript 来获得它,但这没有用,我得到了undefined
data.weather.notes.cities['-temp']
How can I get every value of "-temp"?如何获得“-temp”的每个值?
const temps = data.weather.notes.cities.map(city => city["-temp"]);
console.log(temps); // ["17", "16", "18"]
Of course you can always access to them individually:当然,您始终可以单独访问它们:
const { cities } = data.weather.notes;
console.log(cities[0]["-temp"]); // "17"
Or loop all of them:或循环所有这些:
for (let city of cities) {
console.log("temperature in %s is %s°",
city["-id"], city["-temp"]
);
}
Here is an example for inserting the city's temp into a new array:这是将城市的温度插入新数组的示例:
const newArray= new Array();
data.weather.notes.cities
.forEach(city => newArray.push(city['-temp']))
You could possibly iterate through all the cities and gather the "-temp" keys.您可能会遍历所有城市并收集“-temp”键。
data.weather.notes.cities.forEach(function(element) {
for (var em in element) {
if (em == "-temp")
{
console.log(element[em])
}
}
});
@ZER0 answer is probably the best though. @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 }
You can't use JSON the same way you use jquery selectors.您不能像使用 jquery 选择器一样使用 JSON。 In your case, you need to map your array of cities.在您的情况下,您需要 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"]
See map documentation for further information.有关详细信息,请参阅map文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.