How to use Object.getOwnPropertyNames() and length property In Javascript
To calculate the length of an associative array using Object.getOwnPropertyNames() and the length`property, retrieve an array of all property names using Object.getOwnPropertyNames(), then get the length of that array using the length property.
Example: In this example we calculates the length of an associative array (object) using Object.getOwnPropertyNames() and the length property. It outputs the number of key-value pairs in the object.
let associativeArray = { key1: 'value1', key2: 'value2' };
let length = Object.getOwnPropertyNames(associativeArray).length;
console.log(length);
Output
2
Calculate the length of an associative array using JavaScript
In JavaScript, we have normal arrays in which an element is present at a particular index. Whereas Associative arrays are basically Objects in JavaScript where the index is replaced with user-defined keys. Basically, we can say that it stores Key-Value pairs.
Syntax:
let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'}
Here, arr is the associative array, key1, key2, and key3 are its indexes, and value1, value2, and value3 are its elements.
Example: This is a basic example of the associative property.
let arr = {
"apple": 10,
"grapes": 20
};
arr["guava"] = 30;
arr["banana"] = 40;
console.log("Apple = " + arr.apple)
console.log("Banana = " + arr.banana)
Output
Apple = 10 Banana = 40
Length of an associative array: Like in a normal array, an associative array does not have a length property. So we will see other ways to calculate the length of associative arrays.
To calculate the length of an associative array, we will traverse the array element and count all the keys present in the array.
We can calculate the length of an associative array in the following ways:
Table of Content
- Using hasOwnProperty & for…in loop
- Using the keys Method
- Using Object.entries() Method
- Using Object.getOwnPropertyNames() and length property