How to use a Map for Multiple Values In Javascript
Utilize a Map object to store multiple values for the same key. Initialize the key with an empty array, then push values into it. This approach allows for efficient storage and retrieval of key-value pairs with duplicate keys.
Example: The function addValueToKey adds values to a Map under the same key. For key ‘key’, it stores [‘value1’, ‘value2’]. Printing the map outputs the entries.
let map = new Map();
// Function to add a value to a key
function addValueToKey(key, value) {
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(value);
}
// Add values to the same key
addValueToKey('key', 'value1');
addValueToKey('key', 'value2');
// Print the Map
console.log(Array.from(map.entries()));
Output
[ [ 'key', [ 'value1', 'value2' ] ] ]
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values.
Table of Content
- Using for…of Loop
- Using reduce()
- Using a Map for Multiple Values
- Using forEach()