How to use Array.prototype.forEach() In Javascript
This method demonstrates how to add key-value pairs to a Map by iterating over an array of pairs using Array.prototype.forEach().
Example: In this example, we will use Array.prototype.forEach() to add key-value pairs to a Map.
// Given array of pairs
const pairs = [
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
];
// Create a new Map
const map1 = new Map();
// Use forEach to add each pair to the map
pairs.forEach(([key, value]) => {
map1.set(key, value);
});
// Display the map
console.log(map1);
Output
Map(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }
How to Add a key/value Pair to Map in JavaScript ?
This article will demonstrate how we can add a key-value pair in the JavaScript map. JavaScript Map is a collection of key-value pairs in the same sequence they are inserted. These key values can be of primitive type or the JavaScript object.
All methods to add key-value pairs to the JavaScript Map:
Table of Content
- Map constructor
- Using map set() Method
- Using Map object and spread operator
- Using Array map() Method
- Using Object.entries() and Spread Operator
- Using Array.prototype.forEach()
Contact Us