How to Initialize a Map with Values in JavaScript
Table of Contents
Maps in JavaScript are objects that represent a collection of key-value pairs.
What this means is that you can add new values by inserting them with a unique key.
However, you can alternatively just initialize the map with a set of key-value pairs if you already know what you want to store.
In this post, we'll learn how to initialize a map with values in JavaScript.
Create a Map from an Array
An easy way to initialize a map with values is by creating a new map and pass it an array as the parameter.
When you pass in an array of key-value pairs, the map will automatically create a new key-value pair for each item in the array.
Let's look at an example of this:
JAVASCRIPTconst values = [
["name", "John"],
["age", 30]
];
Now we can use this to create a new map with the values:
JAVASCRIPTconst values = [
["name", "John"],
["age", 30]
];
const map = new Map(values);
console.log(map);
BASHMap(2) {'name' => 'John', 'age' => 30}
Create a Map from an Object
Alternatively, another way to initialize a map is by passing in an object.
In general, objects in JavaScript are already key-value pairs, so it's easy to use them to initialize a map.
All we need to do is use Object.entries
on the object to convert it into an array of key-value pairs.
Let's first create an example object:
JAVASCRIPTconst values = {
name: "John",
age: 30
};
Now we can use this to create a new map with the values:
JAVASCRIPTconst values = {
name: "John",
age: 30
};
const map = new Map(Object.entries(values));
console.log(map);
BASHMap(2) {'name' => 'John', 'age' => 30}
Conclusion
In this post, we learned how to initialize a map with values in JavaScript by starting with an array or object.
Both of these approaches are good for when you already have the values you want in the map.
Thanks for reading and happy coding!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Getting Started with React