即使缺少密钥,也要遍历JSON对象

史蒂芬

我的JSON具有以下数据:

        {
       "results":[
          {
             "name":"Sydney Showboats",
             "photos":[
                {
                   "photo_reference":"Pic062"
                }
             ]
          },
          {
             "name":"Blue Line Cruises"
          },
          {
             "name":"Rhythmboat Cruises",
             "photos":[
                {
                   "photo_reference":"Pic678"
                }
             ]
          },
          {
             "name":"Flying Fish Restaurant & Bar",
             "photos":[
                {
                   "photo_reference":"Pic345"
                }
             ]
          }
       ],
       "status":"OK"
    }

我试图遍历此JSON,以显示.name div中的每个名称值和.photo div中的每个图像:

$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    $('.name').html('<p>' + data.results[index].name + '</p>');
    $('.photo').html('<img src="' + data.results[index].photos[0].photo_reference + '.jpg">');
  })
});

它可以与名称值一起正常工作,也可以与第一个图像一起工作。但是,由于第二个对象中没有“照片”属性,因此脚本会由于

未捕获的TypeError:无法读取未定义的属性“ 0”。

那么有两种方法可以:删除没有嵌套有照片对象的对象?使用更复杂的循环遍历JSON并存储所有可用图像吗?有什么可行的解决方案可以让我动态显示每个可用的图像?

如果有人能启发我,将不胜感激!

巴勃罗

您要确保迭代中的当前对象包含该属性。检查对象是否包含属性的一种方法是使用in运算符。

$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    if ('photos' in data.results[index] && 'name' in data.results[index]){
      $('.name').html('<p>' + data.results[index].name + '</p>');
      $('.photo').html('<img src="' + 
      data.results[index].photos[0].photo_reference + '.jpg">');
    }
 })

});

运营商文档

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章