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?

4

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is almost exactly how jQuery does it for its isEmptyObject() function
Note if you want it to act the same as Object.keys, you'll have to include a hasOwnProperty check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.