Aproach 2: Using Object.getOwnPropertyNames()
The Object.getOwnPropertyNames() method in JavaScript is a standard built-in object which returns all properties that are present in a given object except for those symbol-based non-enumerable properties.
Example: Object.getOwnPropertyNames(dictionary) in this code retrieves an array of all property names, inclusive of non-enumerable ones; subsequently, the .length property calculates the count of said properties within the array. This count directly represents and signifies: it is indeed the length–or size–of our dictionary. We then proceed to log this result onto the console.
Javascript
const dictionary = { key1: 'value1' , key2: 'value2' , key3: 'value3' }; const length = Object.getOwnPropertyNames(dictionary).length; console.log( "Length of the dictionary:" , length); |
Length of the dictionary: 3
How to Find the Length of JavaScript Dictionary ?
In JavaScript, you may often find a dictionary referred to as an object. Therefore, unlike arrays which have a length property, objects (dictionaries) do not have a built-in length property. However, the “length” of a given dictionary in JavaScript may be determined through counting the pairs of key-value it contains.
Contact Us