Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating an associative array in JavaScript?
In JavaScript, there's no true associative array like in other languages. Instead, you use objects or arrays of objects to achieve similar functionality. JavaScript objects act as associative arrays where you can use string keys to access values.
What are Associative Arrays?
Associative arrays use named keys instead of numeric indexes. In JavaScript, regular arrays have numeric indexes, but objects provide key-value pairs that function like associative arrays.
Method 1: Using Objects
The most common approach is using plain JavaScript objects:
// Creating an associative array using object
var customer = {
"customerId": "customer-1",
"customerName": "David",
"customerCountryName": "US"
};
// Accessing values
console.log(customer.customerName); // Dot notation
console.log(customer["customerId"]); // Bracket notation
David customer-1
Method 2: Using Array of Objects
For multiple records, use an array containing objects:
var customerDetails = [
{
"customerId": "customer-1",
"customerName": "David",
"customerCountryName": "US"
},
{
"customerId": "customer-2",
"customerName": "Bob",
"customerCountryName": "UK"
},
{
"customerId": "customer-3",
"customerName": "Carol",
"customerCountryName": "AUS"
}
];
// Accessing data
for(var i = 0; i < customerDetails.length; i++){
console.log(customerDetails[i].customerName);
}
David Bob Carol
Method 3: Using Map Object
ES6 introduced the Map object for better key-value storage:
var customerMap = new Map();
customerMap.set("customer-1", "David");
customerMap.set("customer-2", "Bob");
customerMap.set("customer-3", "Carol");
// Accessing values
console.log(customerMap.get("customer-1"));
// Iterating through Map
for(let [key, value] of customerMap){
console.log(key + ": " + value);
}
David customer-1: David customer-2: Bob customer-3: Carol
Comparison
| Method | Best For | Key Types |
|---|---|---|
| Objects | Simple key-value pairs | Strings only |
| Array of Objects | Multiple records | Object properties |
| Map | Dynamic keys, iteration | Any type |
Conclusion
JavaScript objects serve as associative arrays for simple key-value storage. Use arrays of objects for multiple records, or Map objects when you need more advanced key-value functionality.
