How to push an associative item into an array in JavaScript?

Estimated read time 1 min read

In JavaScript, arrays are typically used to store a list of items that are indexed by numbers, starting from 0. However, if you want to associate each item with a specific key, you should use an object (also known as a dictionary or hash map) instead of an array.

To add a new key-value pair to an object, you can simply use the following syntax:

const obj = {};
obj['key'] = 'value';

Alternatively, you can use the dot notation to add a new property to an object:

const obj = {};
obj.key = 'value';

Both of these approaches will result in the same object:

  key: 'value'

So, to summarize, if you want to associate items with keys in JavaScript, use an object, not an array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply