Map Object Values

Beginner

This tutorial is from open-source community. Access the source code

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Object.keys() to iterate over the keys of the object.
  3. Use Array.prototype.reduce() to create a new object with the same keys and mapped values using the provided function fn.
  4. The code below demonstrates the implementation of the mapValues function.
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.