Sometimes, we want to turn all the keys of an object to lower case with JavaScript.
In this article, we’ll look at how to turn all the keys of an object to lower case with JavaScript.
How to turn all the keys of an object to lower case with JavaScript?
To turn all the keys of an object to lower case with JavaScript, we can use the Object.entries
and Object.fromEntries
method and the string toLowerCase
method.
For instance, we write
const newObj = Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
);
to call Object.fromEntries
with the array returned by Object.entries
and map
.
Object.entries
returns the key-value pairs in obj
as an array of key-value pair arrays.
Therefore, we can call map
on the returned array to return the lower case version of key k
with k.toLowerCase
.
Then we call Object.fromEntries
to convert the array of key value pairs with the keys in lower case back to an object and assign it to newObj
.
Conclusion
To turn all the keys of an object to lower case with JavaScript, we can use the Object.entries
and Object.fromEntries
method and the string toLowerCase
method.