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
Mapping values to keys JavaScript
In JavaScript, mapping values to keys means creating associations between identifiers (keys) and their corresponding data (values). This is commonly achieved using objects, which store data in key-value pairs for efficient retrieval.
Understanding the Problem
Objects in JavaScript are data structures that store information as key-value pairs. Keys serve as identifiers to access their associated values. There are several ways to access these values, with dot notation and bracket notation being the most common approaches.
For example, with an object const obj = {name: 'John', age: 30}, you can access the name using obj.name or obj['name'].
Using Dot and Bracket Notation
The simplest approach is creating an object with predefined key-value pairs and accessing values directly:
const userMap = {
name: 'Alice',
email: 'alice@example.com',
role: 'developer'
};
// Dot notation
console.log("Name:", userMap.name);
// Bracket notation
console.log("Email:", userMap['email']);
console.log("Role:", userMap.role);
Name: Alice Email: alice@example.com Role: developer
Dynamic Key-Value Mapping
You can also create mappings dynamically by iterating through arrays and building the object programmatically:
const cities = ['New York', 'London', 'Tokyo'];
const cityMap = {};
// Create dynamic key-value pairs
for (let i = 0; i < cities.length; i++) {
cityMap[`city${i + 1}`] = cities[i];
}
console.log("First city:", cityMap.city1);
console.log("Second city:", cityMap['city2']);
console.log("All mappings:", cityMap);
First city: New York
Second city: London
All mappings: { city1: 'New York', city2: 'London', city3: 'Tokyo' }
Using Map Object
JavaScript also provides a built-in Map object for more advanced key-value mapping with better performance for frequent additions and removals:
const userMap = new Map();
// Setting key-value pairs
userMap.set('user1', 'John Doe');
userMap.set('user2', 'Jane Smith');
userMap.set(123, 'Numeric key example');
// Accessing values
console.log("User1:", userMap.get('user1'));
console.log("User2:", userMap.get('user2'));
console.log("Numeric key:", userMap.get(123));
console.log("Map size:", userMap.size);
User1: John Doe User2: Jane Smith Numeric key: Numeric key example Map size: 3
Comparison
| Method | Time Complexity | Use Case |
|---|---|---|
| Object Literal | O(1) access | Simple, predefined mappings |
| Dynamic Object | O(n) creation, O(1) access | Building mappings from arrays |
| Map Object | O(1) access | Complex keys, frequent updates |
Conclusion
JavaScript offers multiple approaches for mapping values to keys. Use object literals for simple cases, dynamic creation for array-based data, and Map objects when you need advanced features or non-string keys.
