How to Get the Length of an Associative Array in JavaScript

08/02/2021

Contents

In this article, you will learn how to get the length of an associative array in JavaScript.

Getting the length of an associative array in JavaScript

To get the length of an associative array in JavaScript, you can use the Object.keys() method or the Object.entries() method. Here’s how to do it:

Using Object.keys()

You can use the Object.keys() method to get an array of all the keys in the object, and then get the length of that array. Here’s an example:

const obj = { foo: 'bar', baz: 'qux' };
const keys = Object.keys(obj);
const length = keys.length;
console.log(length); // output: 2

In the above example, we have an object obj with two key-value pairs. We use the Object.keys() method to get an array of the keys in the object ([‘foo’, ‘baz’]) and store it in the keys variable. Then we get the length of the keys array using the .length property and store it in the length variable. Finally, we log the length variable to the console, which outputs 2.

Using Object.entries()

You can also use the Object.entries() method to get an array of all the key-value pairs in the object, and then get the length of that array. Here’s an example:

const obj = { foo: 'bar', baz: 'qux' };
const entries = Object.entries(obj);
const length = entries.length;
console.log(length); // output: 2

In the above example, we have an object obj with two key-value pairs. We use the Object.entries() method to get an array of the key-value pairs in the object ([[‘foo’, ‘bar’], [‘baz’, ‘qux’]]) and store it in the entries variable. Then we get the length of the entries array using the .length property and store it in the length variable. Finally, we log the length variable to the console, which outputs 2.

Note: The Object.keys() and Object.entries() methods return the keys and values in the order in which they were added to the object. However, it’s important to note that the order of keys in an object is not guaranteed in JavaScript, so you should not rely on the order of the keys returned by these methods.