Skip to content

JavaScript map initialize with values | Code

  • by

You can use the Map() constructor to map initialize with values in JavaScript. You have to pass arrays of key-value pairs, where the first element in the array is the key and the second – is the value.

JavaScript map initialize with values

Simple example code Each key-value pair is added to the new Map. We passed a two-dimensional array to the Map() constructor to initialize it with values.

Let’s see how to create a Map from Object and array.

<!DOCTYPE html>
<html>
<body>
  <script >
    // Create Map from Array
    const map1 = new Map([
      ['country', 'Chile'],
      ['name', 'Tom'],
      ]);

    console.log(map1);
    console.log(typeof(map1))

    // Create Map from Object
    const obj = {name: 'Tom', country: 'Chile'};
    const map2 = new Map(Object.entries(obj));

    console.log(map2);
    console.log(typeof(map2))

  </script>
</body>
</html>

Output:

JavaScript map initialize with values

Use the Object.entries method to create a map from an object.

const obj = {name: 'Tom', country: 'Chile'};

// [['name', 'Tom'], ['country', 'Chile']]
console.log(Object.entries(obj));

Do comment if you have any doubts or suggestions on this Js map basic code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading