javascript tutorial - [Solved-5 Solutions] Efficiently count the number of keys/properties of an object - javascript - java script - javascript array
Problem:
How to efficiently count the number of keys/properties of an object in JavaScript?
Solution 1:
The fastest way to count the number of keys/properties of an object
var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) count++;
click below button to copy the code. By JavaScript tutorial team
Solution 2:
Object.keys(obj).length
click below button to copy the code. By JavaScript tutorial team
Solution 3:
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;
};
}
click below button to copy the code. By JavaScript tutorial team
Solution 4:
If we were using Underscore.js you can use _.size _.size(obj)
Alternatively we can also use _.keys which might be clearer for some:
_.keys(obj).length
Solution 5:
var myObject = new Object();
Object.defineProperty(myObject, "nonEnumerableProp", {
enumerable: false
});
Object.defineProperty(myObject, "enumerableProp", {
enumerable: true
});
console.log(Object.getOwnPropertyNames(myObject).length); //outputs 2
console.log(Object.keys(myObject).length); //outputs 1
console.log(myObject.hasOwnProperty("nonEnumerableProp")); //outputs true
console.log(myObject.hasOwnProperty("enumerableProp")); //outputs true
console.log("nonEnumerableProp" in myObject); //outputs true
console.log("enumerableProp" in myObject); //outputs true