What's the fastest way of detecting the existence of one or more keys inside an object? Is it possible to do it without iterating over the object by using Object.keys().length?
This question is almost identical to How to efficiently count the number of keys/properties of an object in JavaScript?
-
1Are you talking about own properties? Inherited properties? Only enumerable properties?cookie monster– cookie monster2014-01-10 04:01:52 +00:00Commented Jan 10, 2014 at 4:01
-
Yes, you said it yourself...read more here: stackoverflow.com/questions/126100/…NewInTheBusiness– NewInTheBusiness2014-01-10 04:07:03 +00:00Commented Jan 10, 2014 at 4:07
-
@cookiemonster I'm primarily want to know if the object has any properties in general.RienNeVaPlu͢s– RienNeVaPlu͢s2014-01-10 04:11:27 +00:00Commented Jan 10, 2014 at 4:11
-
1Very closely related: “Falsy or empty” in JavaScript: How to treat {} and [] as falseQantas 94 Heavy– Qantas 94 Heavy2014-01-10 04:33:07 +00:00Commented Jan 10, 2014 at 4:33
Add a comment
|
1 Answer
Perhaps use this:
function hasProperties (obj) {
for(var x in obj)
return true;
return false;
}
Yes, admittedly you do have to iterate over the object, but you stop after the first property is found.
2 Comments
mjobrien
This is almost exactly how jQuery does it for its
isEmptyObject() functionQantas 94 Heavy
Note if you want it to act the same as
Object.keys, you'll have to include a hasOwnProperty check.