Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Checking if an object has no properties or if a map/associative-array is empty [duplicate]

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)?

like image 339
Vivin Paliath Avatar asked Aug 06 '10 19:08

Vivin Paliath


People also ask

How do you check if an object has no properties in JavaScript?

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.

How do you check an object is empty or not in JavaScript?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

How do you check if an array of objects is empty in JavaScript?

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.

How do you know if an object has no property?

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.


1 Answers

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.

like image 141
chryss Avatar answered Oct 15 '22 19:10

chryss