Maps - Iteration
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.
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);
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
.
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));
This means that there is an easy way to convert objects to maps.
const openingHoursMap = new Map(Object.entries(openingHours));
console.log(openingHoursMap);
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.
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
}
}
Let's log the question above the options
console.log(`Question: ${quizzQuestionsMap.get('question')}`); // Question: What is the capital of France?
...
To get the answer from the user, let's use a prompt.
/**
* 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}`);
/**
* 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')));
To finish this lecture, let me show you how we can convert a map back to an array. So basically to this structure:
[
['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:
const quizzQuestionsArray = Array.from(quizzQuestionsMap);
// or
const quizzQuestionsArray = [...quizzQuestionsMap];
console.log(quizzQuestionsArray);
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.
console.log([...quizzQuestionsMap.entries()]); // Which will be equal to the array above
console.log([...quizzQuestionsMap.keys()]);
console.log([...quizzQuestionsMap.values()]);
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.