Possible Duplicate:
How do I test for an empty Javascript object from JSON?
Is there an easy way to check if an object has no properties, in Javascript? Or in other words, an easy way to check if a map/associative array is empty? For example, let's say you had the following:
var nothingHere = {}; var somethingHere = {foo: "bar"};
Is there an easy way to tell which one is "empty"? The only thing I can think of is something like this:
function isEmpty(map) { var empty = true; for(var key in map) { empty = false; break; } return empty; }
Is there a better way (like a native property/function or something)?
keys() method to check if there are any properties defined in an object. It returns an array of object's own keys (or property names). We can use that array to check if it's length is equal to 0 . If it is, then it means the object has no properties.
keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.
To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.
We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.
Try this:
function isEmpty(map) { for(var key in map) { if (map.hasOwnProperty(key)) { return false; } } return true; }
Your solution works, too, but only if there is no library extending the Object
prototype. It may or may not be good enough.
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