Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a javascript object contains null value or it itself is null

Tags:

javascript

Say I'm accessing a JavaScript Object called jso in Java and I'm using the following statement to test if it's null

if (jso == null)

However, this statement seems to return true when jso contains some null values, which is not what I want.

Is there any method that can distinguish between a null JavaScript Object and a JavaScript Object that contains some null values?

Thanks

like image 738
mpang Avatar asked Oct 29 '11 01:10

mpang


People also ask

IS null == null in JavaScript?

null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null . typoef operator is useful to determine the type of a variable (number, string, boolean).

How do you check if an object is null or not?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.

IS null considered an object in JavaScript?

Null is not an object in JavaScript!

Is null or empty in JS?

For verifying whether the variable is null or empty, you can use the length property of the JavaScript or the strict equality (===) operator with the OR (||) operator in JavaScript.


2 Answers

To determine whether the target reference contains a member with a null value, you'll have to write your own function as none exist out of the box to do this for you. One simple approach would be:

function hasNull(target) {
    for (var member in target) {
        if (target[member] == null)
            return true;
    }
    return false;
}

Needless to say, this only goes one level deep, so if one of the members on target contains another object with a null value, this will still return false. As an exmaple of usage:

var o = { a: 'a', b: false, c: null };
document.write('Contains null: ' + hasNull(o));

Will print out:

Contains null: true

In contrast, the following will print out false:

var o = { a: 'a', b: false, c: {} };
document.write('Contains null: ' + hasNull(o));
like image 85
Kirk Woll Avatar answered Nov 15 '22 23:11

Kirk Woll


This is just for your reference. Do not upvote.

var jso;
document.writeln(typeof(jso)); // 'undefined'
document.writeln(jso); // value of jso = 'undefined'

jso = null;
document.writeln(typeof(jso)); // null is an 'object'
document.writeln(jso); // value of jso = 'null'

document.writeln(jso == null); // true
document.writeln(jso === null); // true
document.writeln(jso == "null"); // false

http://jsfiddle.net/3JZfT/3/

like image 29
Samuel Liew Avatar answered Nov 15 '22 23:11

Samuel Liew