Javascript Maps

Maps are a new data strucure in es6 designed to store key / value pairs.

Maps are designed to replace object literals for storing key/value pairs. Using the new map data structure is beneficial because it gives us access to some handy properties. These properties allow us to iterate over maps, use any data type as keys and easily add or remove data.

Storing key/value pairs (the old way)

We can use object literals to store key/value pairs. For example:

                     var oldCar = {
                        "make": "Toyota",
                        "model": "Corolla",
                        "year":  1999
                    console.log(oldCar.year) // retrieve the value of the year of the oldCar.

Creating a map to store key/value pairs (the new way)

Create a new instance of a Map. Use the `set` keyword to set the key value pairs and the `get` keyword to retrieve values. For example:

                     // the new way
                        let newCar = new Map(); // create a new instance of Map.
                        // set the key / value pairs

                        console.log(newCar.get('year')); // retrieve the value of the year of the newCar.

The size method for Maps

Determine the number of unique keys in the Map

                     console.log(newCar.size); // checks size of the map. Expected output: 3;

                    console.log(newCar.size); // expected output still 3. We just overwrote the value for the key `year`

Delete elements from a Map

The delete property of maps lets you remove a key from the map.

                     // use the `delete` method to remove coffee in the shopping cart

Check to see if key exists in the Map

The `has` property of sets lets you check if items are in the set.

                     // use the `has` method to check if these keys exist in the newCar map.
                        console.log(newCar.has('year')); // true
                        console.log(newCar.has('brakes')); // false

Dash-Intel is a Power BI and Tableau resource site for data visualization and building BI dashboards.

Data Analyst & Consultant

Copyright 2015-2023 Terms