Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  168] [ 7]  / answers: 1 / hits: 59093  / 14 Years ago, fri, august 6, 2010, 12:00:00

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


More From » dictionary

 Answers
13

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.


[#95999] Wednesday, August 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;