How to Get All Keys from an Associative Array in JavaScript

08/02/2021

Contents

In this article, you will learn how to get all keys from an associative array in JavaScript.

Getting all keys from an associative array in JavaScript

In JavaScript, associative arrays are implemented using objects. Here are some methods you can use to get all keys from an associative array:

Using the Object.keys() method

This method returns an array of all keys of an object. You can use this method to get all keys from an associative array.

Example

const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj);
console.log(keys); // Output: ['a', 'b', 'c']

Using a for…in loop

This loop allows you to iterate over the properties of an object, including its keys. You can use this loop to get all keys from an associative array.

Example

const obj = { a: 1, b: 2, c: 3 };
const keys = [];
for (const key in obj) {
  keys.push(key);
}
console.log(keys); // Output: ['a', 'b', 'c']

Using the Reflect.ownKeys() method

This method returns an array of all keys of an object, including non-enumerable properties. You can use this method to get all keys from an associative array.

Example

const obj = { a: 1, b: 2, c: 3 };
const keys = Reflect.ownKeys(obj);
console.log(keys); // Output: ['a', 'b', 'c']

Note that the methods above will only work for associative arrays implemented using objects in JavaScript. If you have an array with numeric indices, you can simply use the Array.prototype.keys() method to get an iterator of its keys.

Example

const arr = [1, 2, 3];
const keys = arr.keys();
console.log([...keys]); // Output: [0, 1, 2]