Introduction
In this lab, we will explore how to convert an array into an identity object using JavaScript. We will be using the Array.prototype.map() method to create an array of key-value pairs, and then we will use the Object.fromEntries() method to convert this array into an object. This lab will help you understand how to manipulate arrays and objects in JavaScript and how to use these methods to create new objects.
Here's how to convert an array to an identity object
If you want to practice coding, open the Terminal/SSH and type node. To convert an array of values into an object with the same values as keys and values, follow these steps:
- Use
Array.prototype.map()to map each value to an array of key-value pairs. - Use
Object.fromEntries()to convert the array of key-value pairs into an object.
Here's the code:
const toIdentityObject = (arr) => Object.fromEntries(arr.map((v) => [v, v]));
And here's an example:
toIdentityObject(["a", "b"]); // { a: 'a', b: 'b' }
Summary
Congratulations! You have completed the Convert Array to Identity Object lab. You can practice more labs in LabEx to improve your skills.