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.