Tuesday, August 13, 2019

performance - How to efficiently count the number of keys/properties of an object in JavaScript?




What's the fastest way to count the number of keys/properties of an object? It it possible to do this without iterating over the object? i.e. without doing



var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) count++;


(Firefox did provide a magic __count__ property, but this was removed somewhere around version 4.)


Answer



To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, Firefox 4+, or Safari 5+:




Object.keys(obj).length



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...