EN
JavaScript - get object length
3 points
In this article, we would like to show you how to get object length in JavaScript.
Below examples show two ways how to do that:
- Using
Object.keys()
method, - Using
hasOwnProperty()
method.
In this solution we use:
-
Object.keys()
method which returns an array of the given object's own enumerable property names. .length
property to check the number of elements in that array.
Runnable example:
xxxxxxxxxx
1
var object = { 'a':1,'b':2,'c':3 }
2
console.log(Object.keys(object).length); // 3
In this solution, we loop through the object
properties checking whether the object has the specified property as its own with hasOwnProperty()
method and we increase the counter
for every existing property.
xxxxxxxxxx
1
var object = { 'a':1,'b':2,'c':3 }
2
3
var counter = 0;
4
for (var i in object) {
5
if (object.hasOwnProperty(i)) {
6
counter++;
7
}
8
}
9
console.log(counter); // 3