Lowercase Object Keys

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will learn how to convert all the keys of an object to lowercase using JavaScript. We will use Object.keys() and Array.prototype.reduce() to map the keys to an object and String.prototype.toLowerCase() to convert them to lowercase. This technique can be useful when dealing with objects that have inconsistent key casing.


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

Converting Object Keys to Lowercase

To convert all keys of an object to lowercase, follow these steps:

  1. Open the Terminal/SSH to start practicing coding and type node.
  2. Use Object.keys() to obtain an array of the object's keys.
  3. Use Array.prototype.reduce() to map the array to an object.
  4. Use String.prototype.toLowerCase() to lowercase the keys.

Here is an example code that implements these steps:

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

You can then call the lowerize() function with an object as an argument to get a new object with all keys in lowercase. For example:

lowerize({ Name: "John", Age: 22 }); // { name: 'John', age: 22 }

Summary

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

Other JavaScript Tutorials you may like