Map object values .toLowerCase()

30 Apr 2021 in TIL

I recently needed to make sure that all of the values in an object were lower case. If I were dealing with an array I could have used map like so:

js
let values = ["mheap", "DEMO"];
values = values.map((v) => v.toLowerCase());
// [ 'mheap', 'demo' ]

However, when trying this with an object I got an error:

js
let data = {
author: "mheap",
action: "DEMO",
};
data.map((v) => v.toLowerCase());
// Uncaught TypeError: data.map is not a function

To convert all of the values in an object, you need to convert the object to a list of key/value pairs, iterate over that list then zip it back up again:

js
let data = {
author: "mheap",
action: "DEMO",
};
data = Object.fromEntries(
Object.entries(data).map(([key, value]) => [key, value.toLowerCase()])
);
console.log(data);
// { author: 'mheap', action: 'demo' }

How it works

First, we define the initial data:

js
let data = {
author: "mheap",
action: "DEMO",
};

Then we convert the object into key/value pairs:

js
Object.entries(data);
// [ [ 'author', 'mheap' ], [ 'action', 'DEMO' ] ]

Then map over that, using object restructuring to extract the key and value in the arguments passed to the callback:

js
Object.entries(data).map(([key, value]) => {});

Then finally, return a modified entry with the value mapped to lowercase:

js
Object.entries(data).map(([key, value]) => [key, value.toLowerCase()]);
// [ [ 'author', 'mheap' ], [ 'action', 'demo' ] ]

At this point we have the data we need, and we can use Object.fromEntries to convert these key/value pairs back to an object

js
Object.fromEntries([
["author", "mheap"],
["action", "demo"],
]);
// { author: 'mheap', action: 'demo' }