๐ŸŽ‰ We just launched our new React course! Get it with 20% off! ๐ŸŽ‰

How to Create Associative Arrays in JavaScript

Ferenc Almasi โ€ข 2022 July 20 โ€ข ๐Ÿ“– 2 min read
  • twitter
  • facebook

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.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

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!
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

Ezoicreport this ad