[英]Get multiple values in diferrent JSON keys in Javascript
再會,
這是我在 API 中的示例響應,我對結果有些困惑。 items 數組中有多個對象,我想獲得來自 API 的特定響應。 我的問題是如何在 JSON 中獲取多個鍵中的多個值?
items: [ {
"venue": {
"id": "4e82750f8b8185a7c93d3632",
"name": "Puregold Meycauyan",
"contact": {},
"location": {
"crossStreet": "Meycauayan",
"lat": 14.72670029378359,
"lng": 120.96040348293954,
"labeledLatLngs": [
{
"label": "display",
"lat": 14.72670029378359,
"lng": 120.96040348293954
}
],
"cc": "PH",
"city": "Bulacan",
"state": "Bulacan",
"country": "Pilipinas",
"formattedAddress": [
"Meycauayan",
"Bulacan",
"Bulacan",
"Pilipinas"
]
},
"tips": [
{
"id": "4f656942e4b08b4770548244",
"createdAt": 1332046146,
"text": "This grocery opens early and the lines are never long.",
"type": "user",
"canonicalUrl": "https://foursquare.com/item/4f656942e4b08b4770548244",
}
];
}];
我只會得到venue.name、venue.formattedAddress 和tips.text?
我的預期是:
Name: Puregold Meycauyan,
formattedAddress: "Meycauayan, Bulacan, Bulacan, Pilipinas",
Tips: This grocery opens early and the lines are never long.
您可以使用解構賦值來獲取數組或對象的特定元素並將其分配給變量標識符
let items = [{"venue":{"id":"4e82750f8b8185a7c93d3632","name":"Puregold Meycauyan","contact":{},"location":{"crossStreet":"Meycauayan","lat":14.72670029378359,"lng":120.96040348293954,"labeledLatLngs":[{"label":"display","lat":14.72670029378359,"lng":120.96040348293954}],"cc":"PH","city":"Bulacan","state":"Bulacan","country":"Pilipinas","formattedAddress":["Meycauayan","Bulacan","Bulacan","Pilipinas"]},"tips":[{"id":"4f656942e4b08b4770548244","createdAt":1332046146,"text":"This grocery opens early and the lines are never long.","type":"user","canonicalUrl":"https://foursquare.com/item/4f656942e4b08b4770548244"}]}}]; let {name:_name, location:{formattedAddress}, tips:[{text}]} = items[0].venue; console.log(_name, formattedAddress, text);
您需要確保您的 json 包含在大括號中,以及數組中的嵌套對象。 例如
var json = { "items": [{ "venue": { "id": "4e82750f8b8185a7c93d3632", "name": "Puregold Meycauyan", "contact": {} } }] } console.log(json.items[0].venue.name);
獲得預期輸出的方法如下:
var json = { items: [{ "venue": { "id": "4e82750f8b8185a7c93d3632", "name": "Puregold Meycauyan", "contact": { }, "location": { "crossStreet": "Meycauayan", "lat": 14.72670029378359, "lng": 120.96040348293954, "labeledLatLngs": [{ "label": "display", "lat": 14.72670029378359, "lng": 120.96040348293954 }], "cc": "PH", "city": "Bulacan", "state": "Bulacan", "country": "Pilipinas", "formattedAddress": ["Meycauayan", "Bulacan", "Bulacan", "Pilipinas"] }, "tips": [{ "id": "4f656942e4b08b4770548244", "createdAt": 1332046146, "text": "This grocery opens early and the lines are never long.", "type": "user", "canonicalUrl": "https://foursquare.com/item/4f656942e4b08b4770548244", }] } }] }; console.log("Name: " + json.items[0].venue.name + ",\\n" + "formattedAddress: \\"" + json.items[0].venue.location.formattedAddress.toString() + "\\",\\n" + "Tips: " + json.items[0].venue.tips[0].text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.