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
How can I instantiate a dictionary in JavaScript where all keys map to the same value?
In JavaScript, you can create a dictionary (object) where all keys map to the same value using several approaches. This is useful when you need to initialize multiple properties with identical values.
Method 1: Using a for...of Loop
The most straightforward approach is to iterate through an array of keys and assign the same value to each:
const keys = ['Name1', 'Name2', 'Name3'];
const dictionary = {};
for (const key of keys) {
dictionary[key] = 'John';
}
console.log(dictionary);
{ Name1: 'John', Name2: 'John', Name3: 'John' }
Method 2: Using Object.fromEntries() with map()
A more functional approach using Object.fromEntries() combined with map():
const keys = ['Name1', 'Name2', 'Name3'];
const defaultValue = 'John';
const dictionary = Object.fromEntries(
keys.map(key => [key, defaultValue])
);
console.log(dictionary);
{ Name1: 'John', Name2: 'John', Name3: 'John' }
Method 3: Using reduce()
You can also use the reduce() method to build the dictionary:
const keys = ['Name1', 'Name2', 'Name3'];
const defaultValue = 'John';
const dictionary = keys.reduce((acc, key) => {
acc[key] = defaultValue;
return acc;
}, {});
console.log(dictionary);
{ Name1: 'John', Name2: 'John', Name3: 'John' }
Method 4: Using a Helper Function
For reusability, create a helper function:
function createDictionary(keys, value) {
const dictionary = {};
for (const key of keys) {
dictionary[key] = value;
}
return dictionary;
}
// Usage
const userNames = createDictionary(['admin', 'user', 'guest'], 'inactive');
const scores = createDictionary(['player1', 'player2', 'player3'], 0);
console.log(userNames);
console.log(scores);
{ admin: 'inactive', user: 'inactive', guest: 'inactive' }
{ player1: 0, player2: 0, player3: 0 }
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| for...of loop | High | Fast | Simple cases, beginners |
| Object.fromEntries() | Medium | Medium | Functional programming style |
| reduce() | Medium | Fast | Complex transformations |
| Helper function | High | Fast | Reusable code |
Conclusion
The for...of loop is the most straightforward method for creating dictionaries with identical values. Use Object.fromEntries() for a functional approach or create helper functions for reusability across your application.
