Borislav Hadzhiev
Last updated: Oct 29, 2021
Check out my new book
To create a Map
from an array, pass a two dimensional array containing
key-value pairs to the Map()
constructor. The Map
constructor creates a new
Map
and adds each key-value pair to it.
// ✅ from Array of ARRAYS const arr1 = [ ['name', 'Tom'], ['country', 'Chile'], ]; const map1 = new Map(arr1); console.log(map1); // 👉️ {'name' => 'Tom', 'country' => 'Chile'} // ✅ from Array of OBJECTS const arr2 = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; const map2 = new Map( arr2.map(object => [object.key, object.value]) ); console.log(map2); // 👉️ {'name' => 'Tom', 'country' => 'Chile'}
In our first example, we passed a two dimensional array containing key-value
pairs directly to the
Map()
constructor. All key-value pairs got added to the new Map
.
Map()
constructor expects an array of arrays, so we have to somehow make the conversion.We iterated over the array using the Array.map method.
The function we passed to the map
method gets called with each element
(object) in the array.
Array.map()
method returns a new array containing the values that the callback function returned.On each iteration, we return an array containing the key and the value of the object.
const arr2 = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; // 👇️ [ ['name', 'Tom'], ['country', 'Chile'] ] const twoDimensionalArr = arr2.map( object => [object.key, object.value] ); console.log(twoDimensionalArr)
Now we have an array of arrays that we can pass to the Map()
constructor.