Getting the length of a JavaScript object means getting the number of properties in an object.
This is something we might do sometimes.
In this article, we’ll look at how to get the length of a JavaScript object.
Object.keys
The Object.keys
lets us get the non-inherited string keys of an object as an array.
This means we can use the length
property of the returned array to get the length of an object.
This method has been available since ES6, so we can use it safely anywhere.
For instance, we can write:
const obj = {
a: 1,
b: 2
}
const size = Object.keys(obj).length;
console.log(size)
We call Object.keys
with the obj
object to get an array of non-inherited string keys from obj
.
It doesn’t include non-enumerable properties, which are properties that we can’t loop through with the for-in
loop.
Object.getOwnPropertyNames()
We can use the Object.getOwnPropertyNames()
method to get all non-inherited string keys of an object, including non-inherited properties.
For instance, we can write:
const obj = {
a: 1,
b: 2
}
const size = Object.getOwnPropertyNames(obj).length;
console.log(size)
There’s no difference between the previous example and this one since all the properties of obj
are enumerable.
However, if there’re any non-enumerable properties set for an array, then we’ll get different results because of the extra non-enumerable properties returned with Object.getOwnPropertyNames
.
Symbol Keys
The 2 methods above don’t return any symbol keys.
To return symbol keys, we’ve to use the Object.getOwnPropertySymbols
method.
For instance, if we have an object with symbol keys, then we can call this method by writing:
const obj = {
[Symbol('a')]: 1,
[Symbol('b')]: 2
}
const size = Object.getOwnPropertySymbols(obj).length;
console.log(size)
We get the size
is 2 since there’re 2 symbol keys in the object.
If an object has both symbol and string keys, then we can use Object.keys
or Object.getOwnPropertyNames
with Object.getOwnPropertySymbols
.
For instance, we can write:
const obj = {
[Symbol('a')]: 1,
[Symbol('b')]: 2,
c: 3
}
const symbolSize = Object.getOwnPropertySymbols(obj).length;
const stringSize = Object.getOwnPropertyNames(obj).length;
const size = symbolSize + stringSize
console.log(size)
We add symbolSize
and stringSize
together to get the total number of keys in obj
.
So size
is 3.
Conclusion
To get the number of string keys in an object, we can use Object.getOwnPropertyNames
or Object.keys
.
And to get the number of symbol keys of an object, we can use Object.getOwnPropertySymbols
.