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 subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. In associative array, the key-value pairs are associated with : 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: Program to loop through associative array and print keys.
<script> // Script to Print the keys using loop // Associative array var arr = { "Newton": "Gravity", "Albert": "Energy", "Edison": "Bulb", "Tesla": "AC" }; document.write("Keys are listed below <br>"); // Loop to print keys for (var key in arr) { if (arr.hasOwnProperty(key)) { // Printing Keys document.write(key + "<br>"); } } </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 which can be used to get all the keys of array.
Syntax:
Object.keys(obj)
Example: Below program illustrate the use of Object.keys() to accessing the keys of associative array.
<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); document.write("Keys are listed below <br>"); // Printing keys document.write(keys); </script> |
Output:
Keys are listed below Newton, Albert, Edison, Tesla
Recommended Posts:
- How to remove Objects from Associative Array in JavaScript ?
- JavaScript | array.keys()
- How to convert Map keys to an array in JavaScript ?
- How to loop through an associative array and get the key in PHP?
- Multidimensional Associative Array in PHP
- How to remove a key and its value from an associative array in PHP ?
- How to get numeric index of associative array in PHP?
- How to check an array is associative or sequential in PHP?
- Convert an object to associative array in PHP
- Iterate associative array using foreach loop in PHP
- PHP program to add item at the beginning of associative array
- How to access an associative array by integer index in PHP?
- Object.keys( ) In JavaScript
- JavaScript | typedArray.keys() with Example
- Create a comma separated list from an array in JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


