I have to loop through to check an object to set missing arguments.
Initially, I had a check where when Object.keys().length was empty then a missing array was created for that object variable.
the check was
if (!Object.keys(obj).length) {
missing.push(obj);
}
and was working well as obj always had keys, later there were cases where obj was set as {} which obviously doesn't have keys, how can this be checked?
Object.keys(obj).length doesn't work in all browsers because of JScript DontEnum Bug
try with this pure javascript function (updated)
function isEmpty(obj) {
if (obj == null)
return true;
if (obj === undefined)
return true;
if (obj.length === 0)
return true;
if (obj.length > 0)
return false;
for (var key in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
another solution could be
Object.getOwnPropertyNames(obj).length == 0
getOwnPropertyNames returns an array of all properties (enumerable or not) found directly upon a given object.
refer here for getOwnPropertyNames documentation
if you can use jquery there is this function that should help you
jQuery.isEmptyObject(obj);
refer here for documentation
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