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?
asked Jan 10, 2014 at 3:57
-
1Are you talking about own properties? Inherited properties? Only enumerable properties?cookie monster– cookie monster01/10/2014 04:01:52Commented Jan 10, 2014 at 4:01
-
Yes, you said it yourself...read more here: stackoverflow.com/questions/126100/…NewInTheBusiness– NewInTheBusiness01/10/2014 04:07:03Commented Jan 10, 2014 at 4:07
-
@cookiemonster I'm primarily want to know if the object has any properties in general.RienNeVaPlu͢s– RienNeVaPlu͢s01/10/2014 04:11:27Commented Jan 10, 2014 at 4:11
-
1Very closely related: "Falsy or empty" in JavaScript: How to treat {} and [] as falseQantas 94 Heavy– Qantas 94 Heavy01/10/2014 04:33:07Commented Jan 10, 2014 at 4:33
1 Answer 1
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.
answered Jan 10, 2014 at 4:07
-
1This is almost exactly how jQuery does it for its
isEmptyObject()
functionmjobrien– mjobrien01/10/2014 04:30:06Commented Jan 10, 2014 at 4:30 -
Note if you want it to act the same as
Object.keys
, you'll have to include ahasOwnProperty
check.Qantas 94 Heavy– Qantas 94 Heavy01/10/2014 04:35:32Commented Jan 10, 2014 at 4:35
Explore related questions
See similar questions with these tags.
lang-js