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.
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.
if(d. DESCRIPTION == 'null'){ console. log("Its empty");
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.
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
Another syntax from JQuery which is you are not using Prototype or similar and you prefer to use $ rather than jQuery prefix;
$.isEmptyObject( object )
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.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With