TypeError:访问“photo_reference”属性时无法读取未定义的属性“0”

时间:2017-12-24 07:51:17

标签: javascript arrays json

以下是我从Google Places API获得的JSON。用JSON.parse(body)解析Json。 “结果”键是我正在循环访问照片属性的对象数组。希望代码现在更清晰。我已经粘贴了我从api调用中获得的有效JSON。

let resultJSON = JSON.parse(body);
let results = resultJSON["results"];
for (var i = 0; i < results.length; i++) { 
   let name = results[i]["name"];
   console.log(results[i].photos[0].photo_reference);
}

尝试访问photo_reference属性,如此

order by clause

1 个答案:

答案 0 :(得分:0)

以下是一个片段,显示您的更新代码正在运行。

&#13;
&#13;
let resultJSON = {
  "html_attributions": [],
  "next_page_token": "CqQCGwEAAI5PpCTJI6Qoa1CD9iA4EpJha6t0gMlZ3I3DpOIVgE1BUYh5NNI0lXRuvAltI8RhOilTNJggXsR3TEP2C6hoIsibEWZXnZClbEcZzes7LGqJuQ0heJWipe7RNbxq8S8zuao1HWfECs11i44WO0Luv-4bYx5GlCEj6Wl07LitkzwG4u0e4FyIHogyaShky5Awd44ZyOcqKzy7wYBr7p37j6A6PMdR7zn7cMWQKiVolfHQbFZerVJ3JJ5MiKSshocG189wPKjqJzSACE6W19LmZ7TIMB9qm7jQANNQStrsq7rYAWIBQ-UqJ_6Hv9jv1xL7eRQ9bkyR17u7xPZWfeCU69u_PQmGvuvSWNJDvNUuoI-uwLc_RhgTZp26kyzMlXwYHRIQXy13ridwzgvlBU8ez_y-WBoUcBN7UvN8Q8iuDyS_LjXEWmT_sIk",
  "results": [{
    "geometry": {
      "location": {
        "lat": 28.615572,
        "lng": 77.3468
      },
      "viewport": {
        "northeast": {
          "lat": 28.6169209802915,
          "lng": 77.34814898029151
        },
        "southwest": {
          "lat": 28.6142230197085,
          "lng": 77.34545101970849
        }
      }
    },
    "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
    "id": "dea8496f678dc1f01381a85298e37a0905a3ca11",
    "name": "Malabar Junction Restaurant",
    "opening_hours": {
      "open_now": true,
      "weekday_text": []
    },
    "photos": [{
      "height": 746,
      "html_attributions": [
        "\u003ca href=\"https://maps.google.com/maps/contrib/117230637789134827076/photos\"\u003eSwati\u003c/a\u003e"
      ],
      "photo_reference": "CmRaAAAArbpjr1fjNp2Fc4ww8Vkgrzzzt5aHEvACzEZFa-XCJU3Fw2JqFLSDo64jlFWwDZwdYaFP_cIgdqI37TJ25mVB2W_rtoTv_aI0LJGgnh_P4-UF7u45ZvqdM-bE4ljYD2yyEhDjv-4AWC5AKcE713GL1qAsGhQjAN2oS1KWv52f8XsjEK3Pmnv53w",
      "width": 750
    }],
    "place_id": "ChIJx6qqqj3lDDkRcBw22oTfWgk",
    "reference": "CmRRAAAAZBpNfAiO2G_y57bLoFTSM28MG4xUi-VAg3kJgV2ZzksdhpzySwxdPNdPP1paEIE46i70oxgLHliUcEjxalukNEyhN85J-ryRbXVVMkg4Tz-MGBGhgVur7SV5b4IFePnfEhABXu9pHswL4Up5w-k9td94GhSDs13DRQVxPOpI8iWqUbLyd_WJUg",
    "scope": "GOOGLE",
    "types": ["restaurant", "food", "point_of_interest", "establishment"],
    "vicinity": "62, 8, Rani Jhansi Marg, Block 10, Sector 10, Noida"
  }],
  "status": "OK"
}

let results = resultJSON["results"];
for (var i = 0; i < results.length; i++) {
  let name = results[i]["name"];
  console.log(results[i].photos[0].photo_reference);
}
&#13;
&#13;
&#13;