Get an object's length in JavaScript
An object is not an iterable, so we can't find its length directly; however, there's an easy solution
By: Ajdin Imsirovic 21 January 2021
To get the length of an object in JS, we use Object.keys()
to get an array of our object’s own properties’ keys. Then we can easily return the length
value.
To get the length of an array, we use the built in length
property:
However, we don’t have the length
property on objects:
1
2
3
4
5
let tesla = {
model: 'Model 3',
mileage: 100
}
tesla.length; // undefined
To go around this, we can use the keys()
static method on the Object
object. This method takes an object and returns an array of that object’s own keys:
Since the keys()
method returns an array data structure, now it’s easy to count the number of members of the returned array:
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.