Introduction
In this lab, we will be working on a JavaScript programming exercise that focuses on mapping the values of an object using a provided function. The purpose of this exercise is to help you gain a better understanding of how to use Object.keys() and Array.prototype.reduce() to create a new object with the same keys and mapped values. By the end of this lab, you will be able to apply this knowledge to solve more complex problems in your own projects.
Function to Map Object Values
To map the values of an object using a provided function to generate a new object with the same keys, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Object.keys()to iterate over the keys of the object. - Use
Array.prototype.reduce()to create a new object with the same keys and mapped values using the provided functionfn. - The code below demonstrates the implementation of the
mapValuesfunction.
const mapValues = (obj, fn) =>
Object.keys(obj).reduce((acc, k) => {
acc[k] = fn(obj[k], k, obj);
return acc;
}, {});
Here is an example usage of the mapValues function:
const users = {
fred: { user: "fred", age: 40 },
pebbles: { user: "pebbles", age: 1 }
};
mapValues(users, (u) => u.age); // { fred: 40, pebbles: 1 }
Summary
Congratulations! You have completed the Map Object Values lab. You can practice more labs in LabEx to improve your skills.