Uppercase 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 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.


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

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.

Other JavaScript Tutorials you may like