HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Uppercase or lowercase object keys in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptobjectuppercaselowercasekeys

Problem

Data processing often requires transformation of structures to conform to a specific format. A very simple example of this is converting all the keys of an object to upper or lower case, an easy task for JavaScript.
In order to convert all the keys of an object to upper case, we first need to obtain an array of the object's keys, using Object.keys(). Then, use Array.prototype.reduce() to map the array to an object, using String.prototype.toUpperCase() to uppercase the object's keys.
Similarly, to convert all the keys of an object to lower case, we can use the same approach. The only notable difference is that we use String.prototype.toLowerCase() to lowercase the object's keys.

Solution

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

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


Similarly, to convert all the keys of an object to lower case, we can use the same approach. The only notable difference is that we use String.prototype.toLowerCase() to lowercase the object's keys.

Code Snippets

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

upperize({ Name: 'John', Age: 22 }); // { NAME: 'John', AGE: 22 }
const lowerize = obj =>
  Object.keys(obj).reduce((acc, k) => {
    acc[k.toLowerCase()] = obj[k];
    return acc;
  }, {});

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

Context

From 30-seconds-of-code: upperize-lowerize-object-keys

Revisions (0)

No revisions yet.