2

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?

Community
  • 1
  • 1
RienNeVaPlu͢s
  • 6,574
  • 6
  • 36
  • 72
  • 1
    Are you talking about own properties? Inherited properties? Only enumerable properties? – cookie monster Jan 10 '14 at 04:01
  • Yes, you said it yourself...read more here: http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip – NewInTheBusiness Jan 10 '14 at 04:07
  • @cookiemonster I'm primarily want to know if the object has any properties in general. – RienNeVaPlu͢s Jan 10 '14 at 04:11
  • 1
    Very closely related: [“Falsy or empty” in JavaScript: How to treat {} and \[\] as false](http://stackoverflow.com/questions/19476236/falsy-or-empty-in-javascript-how-to-treat-and-as-false) – Qantas 94 Heavy Jan 10 '14 at 04:33

1 Answers1

3

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.

p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
  • 1
    This is almost exactly how [jQuery does it](https://github.com/jquery/jquery/blob/7e8a91c205723f11cd00c8834f348a649ab15926/src/core.js#L246) for its `isEmptyObject()` function – mjobrien Jan 10 '14 at 04:30
  • Note if you want it to act the same as `Object.keys`, you'll have to include a `hasOwnProperty` check. – Qantas 94 Heavy Jan 10 '14 at 04:35