[英]How to avoid undefined in object key with no value?
I'm trying to iterate an object like this: 我正在尝试迭代这样的对象:
0: Object
appointments: Array[2]
unavailables: Array[2]
0: Object
1: Object
book_datetime: "2015-10-22 02:46:23"
data: "0"
end_datetime: "2015-10-22 13:00:00"
hash: null
id: "21"
id_google_calendar: null
id_services: null
id_users_customer: null
id_users_provider: "87"
is_unavailable: "1"
notes: "Nessuna"
resource_id: "0"
start_datetime: "2015-10-22 12:00:00"
__proto__: Object
length: 2
__proto__: Array[0]
__proto__: Object
1: Object
appointments: Array[1]
unavailables: Array[0]
length: 0
__proto__: Array[0]
__proto__: Object
length: 2
__proto__: Array[0]
in this way: 通过这种方式:
$.each(response, function(_, obj)
{
$.each(obj, function(key, val)
{
if (key === 'unavailables')
{
console.log("=> ", val[0]['id']);
}
});
});
Now all working fine but how you can see the second array contain unavailables length = 0
, when the loop is on here I get 现在一切正常,但你怎么看第二个数组包含unavailables length = 0
,当循环在这里我得到
Cannot read property 'id' of undefined 无法读取未定义的属性“id”
How can avoid this? 怎么能避免这个? There is a method that check if the current key has contain value or not? 有一种方法可以检查当前密钥是否包含值?
I'd probably go for another check before accessing val
: 我可能会在访问val
之前再去检查一下:
if (key === 'unavailables' && val && val.length)
{
console.log("=> ", val[0]['id']);
}
You can try the following. 您可以尝试以下方法。 If val[0]
doesn't exist, it will be replaced with an empty hash, that will respond to ['id']
with undefined
(but avoid errors.) 如果val[0]
不存在,它将被替换为空哈希,它将以undefined
响应['id']
(但避免错误。)
(val[0] || {})['id']
Try checking if val[0]['id'])
exists: 尝试检查val[0]['id'])
存在:
if (key === 'unavailables' && val[0]['id'])){
}
Check if the length
property of val
as such 检查val
的length
属性是否如此
if (val.length > 0) {
console.log("=> ", val[0]['id']);
} else {
// contains no value
}
The existing answers work, but I'd like to point out the fact that your approach is not optimal: you iterate over all properties of all obj
s. 现有的答案有效,但我想指出你的方法不是最优的事实:你迭代所有obj
的所有属性。
In fact you don't need to do that; 事实上你不需要这样做; you can access the unavailables
property directly. 您可以直接访问unavailables
属性。 Your entire code could therefore be reduced to this: 因此,您的整个代码可以简化为:
$.each(response, function(_, obj)
{
var val = obj.unavailables;
if (val && val[0]) {
console.log("=> ", val[0].id);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.