How to Create Associative Arrays in JavaScript

Ferenc Almasi • 2022 July 20 • 📖 2 min read

Associative arrays are a collection of key-value pairs, a type of array where named keys are used in place of numbered indexes. Unlike other programming languages, JavaScript does not have associative arrays. Instead, objects can be used.

const user = {
    name: 'John',
    age: 30,
    job: 'Developer'
}
Use object in place of associative arrays in JavaScript
Copied to clipboard!

Note that objects are denoted by curly braces, and named keys are used instead of indexes. Each key with its value is called a property. To add new properties (entries) to the object, you can use either a dot or bracket notation.

// Using dot notation
user.role = 'admin'

// Using bracket notation
user['role'] = 'admin'
Bracket notation requires the key to be a string
Copied to clipboard!

In general, you want to use the dot notation. When you are working with variables and need dynamic names for your object properties, that's when the bracket notation can come in handy.

const property = 'role'

// The user object will now have a "role" property
user[property] = 'admin'
Using a variable for creating an object property
Copied to clipboard!

Make sure you follow the same naming rules for object properties that you would follow for variables. For example, you cannot start the name of a property with a number.


Traversing with Objects

As objects work quite differently compared to arrays, it means you cannot traverse through objects in the same way you would do with an array.

To loop through an object, you can use a combination of Object.keys, and a forEach loop in the following way:

// This will log out
// - name John
// - age 30
// - job Developer
Object.keys(user).forEach(key => console.log(key, user[key]))
Copied to clipboard!

Object.keys return an array of strings, containing the named keys of the object. We can also use this to get the length of an object if needed.

// Returns the length of the object based on the number of keys
Object.keys(user).length
Copied to clipboard!

We can also get only the values using Object.values, and we can also convert the key-value pairs into arrays using Object.entries.

// Returns ['name', 'age', 'job']
Object.keys(user)

// Returns ['John', 30, 'Developer']
Object.values(user)

// Returns [['name', 'John'], ['age', 30], ['job', 'Developer']]
Object.entries(user)
Copied to clipboard!
Remove ads
Remove ads

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
🎉 Thank you for subscribing to our newsletter. x