30秒学会 JavaScript 片段 · 2018年7月10日

30秒学会 JavaScript 片段 – lowercaseKeys

Creates a new object from the specified object, where all the keys are in lowercase.

Use Object.keys() and Array.prototype.reduce() to create a new object from the specified object.
Convert each key in the original object to lowercase, using String.toLowerCase().

代码片段

const lowercaseKeys = obj =>
  Object.keys(obj).reduce((acc, key) => {
    acc[key.toLowerCase()] = obj[key];
    return acc;
  }, {});

使用样例

const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};