How To Get a List of Associative Array Keys in JavaScript?

Associative Array: It is simply a set of key-value pairs. The value is stored in association with its key and if you provide the key the array will return the value. This is all a PHP associative array is and the name comes from the association between the key and the value. For example, to store the data of customers in an array, a numerically indexed array would not be good practice and easy to handle.

Now the question is how to get a list of associative array keys? We can get the keys of it using Object.keys() function. Object.keys() is an inbuilt function of JavaScript to get all the keys of an array.

Below code, snippet explains the use of Object.keys() to access the keys.

// Associative Array
const arr = {
    "firstName" : "John",
    "lastName" : "Doe",
    "job" : "Developer"
}

// Get the keys
const keys = Object.keys(arr);

// Printing keys
console.log(keys);

Output:
[“firstName”, “lastName”, “job”]

The same result can be achieved by another approach. By iterating the array as shown below:

// Loop to print keys
const keys = [];
for (let key in arr) {
    if (arr.hasOwnProperty(key)) {
        // Pushing key into an array
        keys.push(key);
    }
}

// Printing Keys
console.log(keys);

Output:
[“firstName”, “lastName”, “job”]

So we got the same result as compared to the first approach.

Leave a Reply