Uppercase Object Keys

Beginner

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

Introduction

In this lab, we will explore how to convert all the keys of an object to uppercase in JavaScript. You will learn how to use Object.keys() and Array.prototype.reduce() to create a new object with all the keys converted to uppercase letters. This technique can be useful in various scenarios where you need to standardize the keys of an object for consistency and ease of use.

How to Uppercase Object Keys in JavaScript

To convert all the keys of an object to upper case in JavaScript, follow these steps:

  1. Use Object.keys() to get an array of the object's keys.
  2. Use Array.prototype.reduce() to map the array to an object.
  3. Use String.prototype.toUpperCase() to uppercase the keys.

Here's the code:

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

To test the function, you can call it like this:

upperize({ Name: "John", Age: 22 }); // { NAME: 'John', AGE: 22 }

Summary

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