The best choice to find the length of a JavaScript Object is to use the Object.keys().length approach. It counts the number of keys in the object. There is no built-in property to get it.
There are other options, such as using Object.values().length or Object.entries().length to get the length, but these are not efficient methods.
Using Object.keys().length
The Object.keys() method returns an array of the object’s own enumerable string-keyed property names, and applies the .length property to that array, which returns the length of the array.
const obj = { a: 1, b: 2, c: 3 }; console.log(Object.keys(obj).length); // Output: 3
In the above code, the input object contains keys “a”, “b”, and “c”, and hence its length is 3.
Empty object
If the input object is empty, it does not contain any key-value pairs, and therefore, it returns a length of 0.
const empty_obj = {}; console.log(Object.keys(empty_obj).length); // Output: 0
Object with nested properties
If the object contains nested properties, it only counts the top-level keys, as the inner objects are considered values.
const nested_obj = { x: { y: 1 }, z: 2 }; console.log(Object.keys(nested_obj).length); // Output: 2
In the above code, it only counts keys “x” and “z”. Hence, its count is 2.
Inherited properties
The Object.keys().count does not count inherited properties from the parent object. It only counts its own properties.
function Parent() { } Parent.prototype.inherited = 'from prototype'; const child = new Parent(); child.own = 'mine'; console.log(Object.keys(child).length); // Output: 1
In this code, we defined an “inherited” property in the Parent prototype. So, when we created an object of it, the child object does not own the inherited property. It is the Parent’s property.
So, the child has only “own” property and its count is 1.
Using Object.values().length
You can also use the Object.values() method to retrieve the values in an array format and then use the .length property to count the number of values, which is the length of the Object.
It works the same as Object.keys().length since every key has a value.
const obj = { a: 1, b: 2, c: 3 }; const length = Object.values(obj).length; console.log(length); // Output: 3
Using Object.entries().length (Extra approach)
The Object.entries() method returns an array of [key, value] pairs of the input object, and with the help of the .count property, we can get the length of the object.
const obj = { a: 1, b: 2, c: 3 }; console.log(Object.entries(obj).length); // Output: 3
It is helpful when you want to process key-value pairs, and it ignores non-enumerable symbols and inherited properties.
That’s it!