Shaggy
Shaggy

Reputation: 5790

check null object in jquery each function

I want to loop through each key value json element and print it.but some of the keys has null values also.

Hence $.each is giving error TypeError: obj is null

I dont want to remove null keys from object and not want to print null object in html variable. I want to check for null object in $.each function

Fiddle Demo -> http://jsfiddle.net/paxg89q0/4/

Code:

var s={"CategoryID":"1","Name":"TCS","ID":"23","Type":"Pay","AccountNo":"1234567890","Authenticator":"{\"EmailAddress\":\"dfgsdfgsdfg\",\"MobileNumber\":\"98-7698769\",\"UniqueID\":\"9876-8975657-6\"}","AddBill":null,"PartnerID":null,"ShortName":null,"Token":"8FB91DE6"};
var html;
$('div').html(getKeyValueJson(s));

function getKeyValueJson(obj) {
    $.each(obj, function (key, value) {
        if (typeof value == 'object') {
            getKeyValueJson(value);
        }
        else {
            html += '<label>' + key + '</label><label>' + value + '</label>';
        }
    });
    return html;
}

Upvotes: 0

Views: 6580

Answers (2)

Fabio
Fabio

Reputation: 1960

In some instances, you may want to execute code if the value is null. Wrap your executable code with this statement:

if (myVal== null) {

}

This statement provides a way to execute code only if myVal is null.

Change your code:

DEMO

 function getKeyValueJson(obj) {
    $.each(obj, function (key, value) {
        if(value)
        {
          if (typeof value == 'object') {
            getKeyValueJson(value);
            }
          else {
            html += '<label>' + key + '</label>' + value + '</label>'; 
           }
        }
    });
    return html;
}

Upvotes: 1

apsillers
apsillers

Reputation: 115940

typeof null returns "object", so null values are being treated as objects.

Since it seems that you want to omit nulls entirely, you can explicitly test for null values at the start of your $.each callback:

$.each(obj, function (key, value) {
    if(value === null) { return; } // skip nulls

...

Upvotes: 2

Related Questions