If you don't care about supporting IE8-, you can easily get the number of properties in an object by applying the following two steps :
- Run either
Object.keys()
to get an array that contains the names of only those properties that are enumerable or Object.getOwnPropertyNames()
if you want to also include the names of properties that are not enumerable.
- Get the
.length
property of that array.
If you need to do this more than once, you could wrap this logic in a function :
function size(obj, enumerablesOnly) {
return enumerablesOnly === false ?
Object.getOwnPropertyNames(obj).length :
Object.keys(obj).length;
}
How to use this particular function :
var myObj = Object.create({}, {
getFoo: {},
setFoo: {}
});
myObj.Foo = 12;
var myArr = [1,2,5,4,8,15];
console.log(size(myObj)); // Output : 1
console.log(size(myObj, true)); // Output : 1
console.log(size(myObj, false)); // Output : 3
console.log(size(myArr)); // Output : 6
console.log(size(myArr, true)); // Output : 6
console.log(size(myArr, false)); // Output : 7
See also this Fiddle for a demo.
Object.keys(obj).length
– Muhammad Umer Feb 25 '15 at 0:14