1

i am having and json file wich is created dynamicaly.

For example

{
    "users": [
        {
            "name": "Bill",
            "surname": "Antony",
            "userPoints": 121,
            "wins": 11,
            "nationality": "English"
        },
        {
            "name": "George",
            "surname": "Peter",
            "userPoints": 1332,
            "wins": 11
        }
    ]
}

As you can see the second object is missing nationality field. So in my code when i am printing with JS Jquery (.each). I am having an 'undedified' print for the second user. How can i check this before it's printed?

EDIT: I am adding the way i am printing the data:

function displayData(array) {
    var list = $("#list").empty();
    $.each(array, function () {
       $("ul").append('<li><span class="num">'+ if(this["nationality"]){ this["nationality"] }+'</span></li>');
    });
}
2
  • if (user.nationality) { console.log(user.nationality)} Commented Jun 25, 2014 at 18:58
  • Loop through it ahead of time and make sure none of the expected properties are undefined? Commented Jun 25, 2014 at 18:59

2 Answers 2

4

undefined equates to false, so you can check the property of the object like this:

$.each(data.users, function(i, item) {
    if (item.nationality) {
        console.log(item.nationality);
    }
});

You could also shorten the if statement to this and get the same result:

item.nationality && console.log(item.nationality);
Sign up to request clarification or add additional context in comments.

3 Comments

+1, I never knew undefined == false. Good information.
@AfzaalAhmadZeeshan Yep, it's a handy quirk of javascript. More info: sitepoint.com/javascript-truthy-falsy
You can't use an if statement within a string concatenation like that.
1

You can use hasOwnProperty(). Documentation.

if(users[0].hasOwnProperty('nationality')){

}

4 Comments

Thank you! That was the solution! Is there anyway to make it search all the fields instead of doing it for one each time?
Well, somehow you need to know what properties to search for. If you know that, you can just iterate through the properties.
Ah allright, so i have to make multiple if statements. That's ok i guess! Thanks again!
Or you can put the properties in an array, and loop through that.

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.