Published on

How to Convert Object Keys to Lowercase in JavaScript

Authors

Here's the snippet from Sindre Sorhus tiny package by lowercase-keys

function lowercaseKeys(object) {
  return Object.fromEntries(
    Object.entries(object).map(([key, value]) => [key.toLowerCase(), value])
  );
}

How does it work?

Let's say we have an the following object

// Our input with mixed key cases
const object = { FOO: true, bAr: false };

// 👇 Converts our object to Array
const arrayOfObjects = Object.entries(object);
// →  [["FOO", true], ["bAr", false]]

const arrayWithLowerCase = arrayOfObjects.map(([key, value]) => [
  key.toLowerCase(),
  value,
]);
// →  [["foo", true], ["bar", false]]

Object.fromEntries(arrayWithLowerCase);
// → {foo:true, bar:false}

Note: This handle only 1 level only. If you want to handle nested keys consider using this with map-obj

Happy converting keys!