Introduction
In this lab, we will explore how to convert an array of strings into an object mapping to true. We will utilize the powerful Array.prototype.reduce() method to achieve this. By the end of this lab, you will be able to efficiently transform an array of strings into an object with key-value pairs, making it easier to work with data in your JavaScript applications.
Converting Array to Flags Object
If you want to start practicing coding, open the Terminal/SSH and type node.
The following function converts an array of strings into an object that maps to true.
To do this, we use Array.prototype.reduce(). This method converts the array into an object, where each array value serves as a key whose value is set to true.
const flags = (arr) => arr.reduce((acc, str) => ({ ...acc, [str]: true }), {});
Here's an example:
flags(["red", "green"]); // { red: true, green: true }
Summary
Congratulations! You have completed the Array to Flags Object lab. You can practice more labs in LabEx to improve your skills.