Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Is 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.)

like image 238
mjs Avatar asked Sep 24 '08 08:09

mjs


People also ask

Which are the different ways to enumerate all properties of an object in JavaScript?

Every property in JavaScript objects can be classified by three factors: Enumerable or non-enumerable; String or symbol; Own property or inherited property from the prototype chain.

How do you check if all object keys has value?

To check if all values in object are equal to true :Use the Object. values() method to get an array of the object's values. Call the every() method on the array. The every method will test if all values in the array are equal to true and will return the result.


2 Answers

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

Object.keys(obj).length 
  • Browser compatibility
  • Object.keys documentation (includes a method you can add to non-ES5 browsers)
like image 113
Avi Flax Avatar answered Sep 22 '22 14:09

Avi Flax


You could use this code:

if (!Object.keys) {     Object.keys = function (obj) {         var keys = [],             k;         for (k in obj) {             if (Object.prototype.hasOwnProperty.call(obj, k)) {                 keys.push(k);             }         }         return keys;     }; } 

Then you can use this in older browsers as well:

var len = Object.keys(obj).length; 
like image 38
Renaat De Muynck Avatar answered Sep 24 '22 14:09

Renaat De Muynck