[英]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.