javascript - json - 查看键是否存在于嵌套数组中

标签 javascript jquery json

我觉得这真的很简单,但我如何检查我的 jSON 数据中是否存在月份。使用 .hasOwnProperty 似乎对我不起作用。我觉得我在这里缺少一些简单的东西。它所做的一切总是默认为 else 子句,即使月份在我的 JSON 中很明显。

JS fiddle :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');
}

感谢代码示例。

最佳答案

monthbirthday 中的一个属性,因此您需要执行如下操作:

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');
}

关于javascript - json - 查看键是否存在于嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25130071/

相关文章:

javascript - 将对象推送到对象数组上会返回数组大小

php - 将用户的 id 放入开放类中

javascript - 使用 jQuery 按值属性对选择选项进行排序

javascript - 在完整网站上搜索并替换为 JQuery、php 或其他内容

javascript - 在 for 循环中设置动态键和值

javascript - jQuery 日期选择器监听器选项

javascript - 在 AJAX 页面上刷新 google adsense

jquery - CodeIgniter-jQuery;显示/隐藏错误类别

javascript - 如何使用 jQuery 制作日历(滑动日期作为轮播)?无格日。只有轮播日

json - 如何将bash中的文件转换为json