Map Object Values

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28482{{"`Map Object Values`"}} javascript/data_types -.-> lab-28482{{"`Map Object Values`"}} javascript/arith_ops -.-> lab-28482{{"`Map Object Values`"}} javascript/comp_ops -.-> lab-28482{{"`Map Object Values`"}} javascript/array_methods -.-> lab-28482{{"`Map Object Values`"}} javascript/higher_funcs -.-> lab-28482{{"`Map Object Values`"}} javascript/destr_assign -.-> lab-28482{{"`Map Object Values`"}} end

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.

Other JavaScript Tutorials you may like