gpt4 book ai didi

javascript - 即使缺少键也遍历 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 09:29:20 24 4
gpt4 key购买 nike

我有一个 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">');
})
});

它可以很好地处理名称值,也可以很好地处理第一张图片。但是,由于第二个对象中没有“照片”属性,脚本会因为

Uncaught TypeError: Cannot read property '0' of undefined.

那么有没有办法:删除没有嵌套照片对象的对象?使用更复杂的循环遍历 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">');
}
})

});

Documentation for in operator

关于javascript - 即使缺少键也遍历 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com