const - JS | lectureData Structures, Modern Operators & Strings

Maps - Iteration

Data Structures, Modern Operators & Strings

In the last lecture, we created an empty map and then added elements to it using the set method. However, there is another way of populating a new map without using the set method. I prefer that because the set method is a bit cumbersome when there are a lot of values to set.

So instead, we can create a new map like this.

script.js
const quizzQuestionsMap = new Map([
  ['question', 'What is the capital of France?'],
  [1, 'Paris'],
  [2, 'Lyon'],
  [3, 'Marseille'],
  ['correct', 1],
  [true, 'Correct!'],
  [false, 'Try again!']
]);

console.log(quizzQuestionsMap);

MAPS-IT - 1

So when creating a new map from scratch, directly in the code, I prefer this way of writing it over the way we did in the previous lecture. But when we keep adding new elements, programmatically using code, the set method is still the way to go.

As an aside, does the above map structure (array of arrays) look similar to you? I hope it does because this is the same array structure returned from calling Object.entries.

script.js
const openingHours = {
  thu: {
    open: 12,
    close: 19,
  },
  fri: {
    open: 11,
    close: 22,
  },
  sat: {
    open: 14,
    close: 23,
  },
};
/**
 * [['thu', { open: 12, close: 19 }], ...]
 *
 * thu = key
 * { open: 12, close: 19 } = value
*/
console.log(Object.entries(openingHours));

MAPS-IT - 2

This means that there is an easy way to convert objects to maps.

script.js
const openingHoursMap = new Map(Object.entries(openingHours));
console.log(openingHoursMap);

MAPS-IT - 3

Keep this small trick here in mind, whenever you need a map, when you already have an object. 😉

Next up, let's talk about iteration, and iteration is possible on maps because, as we already know, maps are also iterables, thus making the for loop also available for them. Let's use the for loop to iterate over our map to print the question options.

script.js
for (const [key, value] of quizzQuestionsMap) {
  // Check if the key is a number then log the option
  if (typeof key === 'number') {
    console.log(`Option ${key}: ${value}`); // Option 1: Paris
  }
}

MAPS-IT - 5

Let's log the question above the options

script.js
console.log(`Question: ${quizzQuestionsMap.get('question')}`); // Question: What is the capital of France?
...

MAPS-IT - 4

To get the answer from the user, let's use a prompt.

script.js
/**
 * We need to convert the answer to a number to compare it to the
 * correct answer in the map object later.
 */
const answer = Number(prompt('Your answer:'));
console.log(`User answer: ${answer}`);

MAPS-IT - 6 MAPS-IT - 7

script.js
/**
 * Check if the answer is eual to the value of the correct key. Then get the
 * value of either the true or false key.
*/
console.log(quizzQuestionsMap.get(answer === quizzQuestionsMap.get('correct')));

MAPS-IT - 8

To finish this lecture, let me show you how we can convert a map back to an array. So basically to this structure:

script.js
[
  ['question', 'What is the capital of France?'],
  [1, 'Paris'],
  [2, 'Lyon'],
  [3, 'Marseille'],
  ['correct', 1],
  [true, 'Correct!'],
  [false, 'Try again!']
];

Here is how we can do that:

script.js
const quizzQuestionsArray = Array.from(quizzQuestionsMap);
// or
const quizzQuestionsArray = [...quizzQuestionsMap];
console.log(quizzQuestionsArray);

MAPS-IT - 9

This wouldn't make much sense right now, but it's still good to know that sometimes you can convert a map to an array.

There are also other methods on maps such as entries, keys and values in case you need them.

script.js
console.log([...quizzQuestionsMap.entries()]); // Which will be equal to the array above
console.log([...quizzQuestionsMap.keys()]);
console.log([...quizzQuestionsMap.values()]);

MAPS-IT - 10

Now you might be wondering when I should use maps? And when should I use objects? Because they are pretty similar. Well, that's what the next lecture is all about. I will help you choose between all the data structures, including even arrays and sets.