Introduction
In this lab, we will learn how to map the values of an array to an object using a function in JavaScript. The lab will walk you through the process of using Array.prototype.reduce() to apply a function to each element in an array and combine the results into an object. You will also learn how to use the element as the key and the result of the function as the value for each property.
Mapping Array to Object
To map the values of an array to an object using a function, follow these steps:
- Open the Terminal/SSH and type
nodeto start coding practice. - Use
Array.prototype.reduce()to applyfnto each element inarrand combine the results into an object. - Use
elas the key for each property and the result offnas the value.
Here is an example code snippet:
const mapObject = (arr, fn) =>
arr.reduce((acc, el, i) => {
acc[el] = fn(el, i, arr);
return acc;
}, {});
You can use the mapObject function as shown in this example:
mapObject([1, 2, 3], (a) => a * a); // { 1: 1, 2: 4, 3: 9 }
Summary
Congratulations! You have completed the Map Array to Object lab. You can practice more labs in LabEx to improve your skills.