How to get a list of associative array keys in JavaScript ?
Associative Array: Associative arrays are used to store key-value pairs. For example, to store the marks of the different subjects of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subjects’ names as the keys in our associative array, and the value would be their respective marks gained. In an associative array, the key-value pairs are associated with a symbol.
Method 1: In this method, traverse the entire associative array using a foreach loop and display the key elements of the array.
Syntax:
for (var key in dictionary) { // do something with key }
Example: In this example, we will loop through the associative array and print keys of the array.
javascript
<script> // Script to Print the keys using loop // Associative array var arr = { "Newton" : "Gravity" , "Albert" : "Energy" , "Edison" : "Bulb" , "Tesla" : "AC" }; console.log( "Keys are listed below" ); // Loop to print keys for ( var key in arr) { if (arr.hasOwnProperty(key)) { // Printing Keys console.log(key ); } } </script> |
Output:
Keys are listed below Newton Albert Edison Tesla
Method 2: Using Object.keys() function: The Object.keys() is an inbuilt function in javascript that can be used to get all the keys of the array.
Syntax:
Object.keys(obj)
Example: Below program illustrates the use of Object.keys() to access the keys of the associative array.
javascript
<script> // Script to Print the keys // using Object.keys() function // Associative array var arr = { "Newton" : "Gravity" , "Albert" : "Energy" , "Edison" : "Bulb" , "Tesla" : "AC" }; // Get the keys var keys = Object.keys(arr); console.log( "Keys are listed below " ); // Printing keys console.log(keys); </script> |
Output:
Keys are listed below Newton, Albert, Edison, Tesla
Please Login to comment...