How to find Object length in JavaScript

In this tutorial, we show you three ways to find the JavaScript object length or size with the help of examples.
  1. Using Object.keys
  2. Using Object.values
  3. Using Object.getOwnPropertyNames
Check out all JavaScript examples at https://www.javaguides.net/p/javascript-tutorial-with-examples.html

1. Using Object.keys

The Object.keys() method accepts the object as an argument and returns the array with enumerable properties.
We know that array has a length property so that by using the Object.keys() method returned array we can get the Object size.
Example:
var user = {
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: '[email protected]',
    age: 29
}

console.log(Object.keys(user).length);
Output:
4

2. Using Object.values

The Object.values() method returns the given object values in an array.
Example:
var user = {
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: '[email protected]',
    age: 29
}

console.log(Object.values(user).length); // size is 4
Output:
4

3. Using Object.getOwnPropertyNames

The Object.getOwnPropertyNames() method returns an array with object keys this method is similar to Object.keys() method.
Example:
var user = {
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: '[email protected]',
    age: 29
}

console.log(Object.getOwnPropertyNames(user).length);
Output:
4

Comments