Asked : Nov 17
Viewed : 26 times
After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
Nov 17
Object.keys will return an Array, which contains the property names of the object. If the length of the array is 0, then we know that the object is empty.,The for…in the statement will loop through the enumerable property of the object., If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty., This is typically the easiest way to determine if an object is empty.
Object.keys
will return an Array, which contains the property names of the object. If the length of the array is 0
, then we know that the object is empty.
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
The for…in statement will loop through the enumerable property of object.
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) return false;
}
return true;
}
If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.
function isEmptyObject(obj) {
return JSON.stringify(obj) === '{}';
}
jQuery.isEmptyObject(obj);
_.isEmpty(obj);
answered Jan 13
You can use lodash library instead of making a plain JS function.
_.isEmpty({}) // true
This will check array and object either they do have values and return boolean.
answered Jan 13
The new Way to check value is if(Object.entries(this.props.myarticle).length===0){ }
here myarticles is object
answered Jan 13