How to get the length of an object with Vanilla JavaScript in 3 ways
In this article, I’ll show you how to get the length of an object with Vanilla JavaScript in 3 ways.
In JavaScript, there’s no direct way to call the length
property on an object.
const planet = {
name: 'Earth',
order: 3,
hasJavaScript: true
}
// Calling length property on planet object will result in undefined
planet.length // undefined
This is due to the object itself does not possess such property.
planet.hasOwnProperty('length') // false
You can, however, convert an object to an array and then use the length
property on it. The JavaScript has three native ways to do so:
1. Object.keys() method
This method returns an array of a given object’s own enumerable property names.
const planet = {
name: 'Earth',
order: 3,
hasJavaScript: true
}
Object.keys(planet) // ['name', 'order', 'hasJavaScript']
Object.keys(planet).length // 3
This approach is fully cross-browser, read full docs on Object.keys() method.
2. Object.values() method
This method returns an array of a given object’s own enumerable property values.
const planet = {
name: 'Earth',
order: 3,
hasJavaScript: true
}
Object.values(planet) // ['Earth', 3, true]
Object.values(planet).length // 3
This method is not supported by Internet Explorer browser. Find out more about Object.values() method.
3. Object.entries() method
This method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.
const planet = {
name: 'Earth',
order: 3,
hasJavaScript: true
}
Object.entries(planet) // [['name', 'Earth'], ['order', 3], ['hasJavaScript', true]]
Object.entries(planet).length // 3
This method is not supported by Internet Explorer browser. Find out more about Object.entries() method.