Categories
JavaScript Answers

How to Turn All the Keys of a JavaScript Object to Lower Case?

Spread the love

Sometimes, we want to turn all the keys of a JavaScript object to lower case.

In this article, we’ll look at how to turn all the keys of a JavaScript object to lower case.

Turn All the Keys of a JavaScript Object to Lower Case

To turn all the keys of a JavaScript object to lower case, we can use the Object.entries method to convert the object to an array with the key-value pair arrays.

Then we can use the JavaScript array map method to map the keys to lower case.

And finally, we use the Object.fromEntries method to convert the mapped key-value pair array back to an object.

For instance, we can write:

const obj = {
  FOO: 1,
  BAR: 2,
  BAZ: 3
}
const newObj = Object.fromEntries(
  Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
);
console.log(newObj)

We have the obj object with property key names that are all in upper case.

To convert all the key names to lower case, we call Object.entries with obj to map all the object properties to key-value pair arrays in an array.

Then we call map with a callback that returns the k key converted to lower case with toLowerCase .

The property value v stays unchanged.

And then we call Object.fromEntries to convert the key-value pair array back to an object and assigned the returned object to newObj.

Therefore newObj is:

{
  "foo": 1,
  "bar": 2,
  "baz": 3
}

according to the console log.

Conclusion

To turn all the keys of a JavaScript object to lower case, we can use the Object.entries method to convert the object to an array with the key-value pair arrays.

Then we can use the JavaScript array map method to map the keys to lower case.

And finally, we use the Object.fromEntries method to convert the mapped key-value pair array back to an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *