Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Object is empty with JavaScript/jQuery

I have an object like this:

ricHistory = {
  name1: [{
    test1: value1,
    test2: value2,
    test3: value3
  }],
  name2: [{
    test1: value1,
    test2: value2,
    test3: value3
  }]
};

Now I want to check if e.g. name2 is empty with Javascript/jQuery. I know the method hasOwnProperty. It work for data.hasOwnProperty('name2') only if the name exists or not, but I have to check if its empty.

like image 296
Artpixler Avatar asked Dec 20 '12 14:12

Artpixler


People also ask

How check object values is empty?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

How check JSON object is empty or not in jQuery?

if(d. DESCRIPTION == 'null'){ console. log("Its empty");

How do you know if an object has no value?

return Object.keys(obj).length === 0 ; We can also check this using Object. values and Object. entries . This is typically the easiest way to determine if an object is empty.


4 Answers

you can do this by jQuery.isEmptyObject()

Check to see if an object is empty (contains no properties).

jQuery.isEmptyObject( object )

Example:

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

from Jquery

like image 122
NullPoiиteя Avatar answered Oct 19 '22 17:10

NullPoiиteя


Another syntax from JQuery which is you are not using Prototype or similar and you prefer to use $ rather than jQuery prefix;

$.isEmptyObject( object )
like image 26
burakakkor Avatar answered Oct 19 '22 16:10

burakakkor


Try this:

if (ricHistory.name2 && 
    ricHistory.name2 instanceof Array &&
    !ricHistory.name2.length) {
   console.log('name2 is empty array');
} else {
   console.log('name2 does not exists or is not an empty array.');
}

The solution above will show you whether richHistory.name2 exists, is an array and it's not empty.

like image 9
Minko Gechev Avatar answered Oct 19 '22 18:10

Minko Gechev


Try this useful function:

function isEmpty(obj) {
if(isSet(obj)) {
    if (obj.length && obj.length > 0) { 
        return false;
    }

    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
            return false;
        }
    }
}
return true;    
};

function isSet(val) {
if ((val != undefined) && (val != null)){
    return true;
}
return false;
};
like image 5
stamat Avatar answered Oct 19 '22 17:10

stamat