We all know that JavaScript Object Notation (JSON) is a powerful and popular data markup language. It is widely used in web development and API design. But what if you wanted to transform a JSON object’s keys and values to lowercase?
Fortunately, there is a simple way to do this. All you need to do is to loop through the object, retrieving each key and value, and then convert it to lowercase using the JavaScript toLowerCase() method.
But what if you do it in a fancy way using reduce?
export const objToLowerCase = (obj) => {
if (!obj) return obj;
return Object.keys(obj).reduce((prev, current) => ({ ...prev, [current.toLowerCase()]: obj[current].toLowerCase() }), {});
};
test("obj to lowercase", () => {
const obj = {
MyKey1: "MY Value 1",
MyKey2: "MY Value 2",
};
const result = objToLowerCase(obj);
expect(result["MyKey1"]).toBeDefined();
expect(result["MyKey1"]).toBe("my value 1");
expect(result["MyKey2"]).toBeDefined();
expect(result["MyKey2"]).toBe("my value 2");
});
Photo by Brett Jordan on Unsplash