How to Get the Length of an Object in Javascript

Monday, April 19, 2021 • One minute to read

Javascriptto-the-point2021javascriptto-the-point2021

The Javascript Object is a collection of key value pair.

1const obj = {
2    key1: value1,
3    key2: value2,
4    length: 10
5};
6
7Object.keys(obj).length // 3 ["key1", "key2", "length"]
8obj.length // 10

The Object.keys(obj) returns the array of the keys of the object.

.length is the function available of array.

If you will try to use .length property then object will find length property or key in the object.

Get object length function

Create a object length function.

 1const obj = {
 2    key1: value1,
 3    key2: value2,
 4    length: 10
 5};
 6
 7const len(obj) {
 8    return Object.keys(obj).length;
 9};
10
11len(obj); // 3

Javascriptto-the-point2021javascriptto-the-point2021

PreviousHow to Remove Falsy Values From an Array in Javascript

NextHow to Check if Object Is Empty in Javascript