1

I feel like this is really simple, but how would I check to see if month exists in my jSON data. Using .hasOwnProperty doesn't seem to be working for me. I feel like I'm missing something simple here. All it does is always default to the else clause even though month is clearly in my 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');
}

Code samples are appreciated.

1
  • data.users[0] doesn't have a property month. data.users[0].birthday does. Commented Aug 5, 2014 at 1:52

1 Answer 1

4

month is a property inside of birthday, so you need to do something like this:

if (data.users[0].birthday.month){
    alert('month exists');
} else {
    alert('month does not exist');
}

Note that if you're not sure whether birthday will always be present, you should do this instead:

if (data.users[0].birthday && data.users[0].birthday.month){
    alert('month exists');
} else {
    alert('month does not exist');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.