Map Object Keys

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to map the keys of an object using a provided function, generating a new object. We will use Object.keys() to iterate over the object's keys and Array.prototype.reduce() to create a new object with the same values and mapped keys using the provided function. By the end of this lab, you will have a solid understanding of how to transform an object's keys using JavaScript.


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-28480{{"`Map Object Keys`"}} javascript/data_types -.-> lab-28480{{"`Map Object Keys`"}} javascript/arith_ops -.-> lab-28480{{"`Map Object Keys`"}} javascript/comp_ops -.-> lab-28480{{"`Map Object Keys`"}} javascript/array_methods -.-> lab-28480{{"`Map Object Keys`"}} javascript/higher_funcs -.-> lab-28480{{"`Map Object Keys`"}} javascript/destr_assign -.-> lab-28480{{"`Map Object Keys`"}} end

Function to Map Object Keys

To map the keys of an object using a provided function and generate a new object, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Object.keys() to iterate over the object's keys.
  3. Use Array.prototype.reduce() to create a new object with the same values and mapped keys using the provided function (fn).

Here's an example implementation of the mapKeys function:

const mapKeys = (obj, fn) =>
  Object.keys(obj).reduce((acc, k) => {
    acc[fn(obj[k], k, obj)] = obj[k];
    return acc;
  }, {});

You can test the function with an example input like this:

mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }

Summary

Congratulations! You have completed the Map Object Keys lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like