![](/img/trans.png)
[英]How can One check to see if a Key exists inside a nested Array Of Objects Using Map
[英]json - See if key exists in nested array
我觉得这真的很简单,但是如何检查jSON数据中是否存在月份。 使用.hasOwnProperty似乎对我不起作用。 我觉得这里缺少一些简单的东西。 即使month很明显在我的JSON中,它所做的一切始终始终默认为else子句。
JS小提琴: http : //jsfiddle.net/8y7rJ/1/
var data={"users":[
{
name:"Ray",
phone:"999-999-9999",
birthday: {
month:"January",
day:12,
year:2012
}
},
{
name:"Joe",
phone:"111-999-9999",
birthday: {
year:1992
}
},
{
name:"James",
phone:"111-111-1111",
birthday: {
year:2012
}
}
]}
if(data.users[0].hasOwnProperty("month")){
alert('month exists');
} else {
alert('month does not exist');
}
代码示例受到赞赏。
month
是birthday
的属性,因此您需要执行以下操作:
if (data.users[0].birthday.month){
alert('month exists');
} else {
alert('month does not exist');
}
请注意,如果不确定birthday
是否总是存在,则应改为:
if (data.users[0].birthday && data.users[0].birthday.month){
alert('month exists');
} else {
alert('month does not exist');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.