To convert an array of key-value pairs to a map in JavaScript, you can iterate over the array and insert each key-value pair into the map. This method allows you to create a map from a collection of key-value pairs stored in an array.
We can convert an array of key-value pairs to a map in JavaScript by iterating over the array and adding each key-value pair to the map.
For example,
pairs
. In this example, the pairs are represented as arrays with two elements: a key and a value.myMap
to store the key-value pairs.forEach
method and add each pair to the map.console.log
function to verify the conversion.const pairs = [
[1, 10],
[2, 20],
[3, 30],
[4, 40],
[5, 50]
];
// Declare an empty map to store the key-value pairs
const myMap = new Map();
// Iterate over the array and add each pair to the map
pairs.forEach(([key, value]) => {
myMap.set(key, value);
});
// Print the resulting map
console.log('Map from array of pairs:');
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Map from array of pairs: 1: 10 2: 20 3: 30 4: 40 5: 50
We can convert an array of objects with key and value properties to a map in JavaScript by iterating over the array and adding each object's key-value pair to the map.
For example,
pairs
. In this example, each object has key
and value
properties.myMap
to store the key-value pairs.forEach
method and add each object's key-value pair to the map.console.log
function to verify the conversion.const pairs = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
{ key: 4, value: 40 },
{ key: 5, value: 50 }
];
// Declare an empty map to store the key-value pairs
const myMap = new Map();
// Iterate over the array and add each object's key-value pair to the map
pairs.forEach(({ key, value }) => {
myMap.set(key, value);
});
// Print the resulting map
console.log('Map from array of objects:');
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Map from array of objects: 1: 10 2: 20 3: 30 4: 40 5: 50
We can convert a list of key-value pairs to a map in JavaScript by iterating over the list and adding each key-value pair to the map.
For example,
pairs
. In this example, the pairs are represented as arrays with two elements: a key and a value.myMap
to store the key-value pairs.forEach
method and add each pair to the map.console.log
function to verify the conversion.const pairs = [
[1, 10],
[2, 20],
[3, 30],
[4, 40],
[5, 50]
];
// Declare an empty map to store the key-value pairs
const myMap = new Map();
// Iterate over the list and add each pair to the map
pairs.forEach(([key, value]) => {
myMap.set(key, value);
});
// Print the resulting map
console.log('Map from list of pairs:');
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Map from list of pairs: 1: 10 2: 20 3: 30 4: 40 5: 50
In this tutorial, we learned How to Convert an Array of Key-Value Pairs to a Map in JavaScript language with well detailed examples.