30秒学会 JavaScript 片段 · 2022年12月25日

30秒学会 JavaScript 片段 – Rename object keys

Replaces the names of multiple object keys with the values provided.

  • Use Object.keys() in combination with Array.prototype.reduce() and the spread operator (...) to get the object’s keys and rename them according to keysMap.

代码实现

const renameKeys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );

const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj);
// { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }

翻译自:https://www.30secondsofcode.org/js/s/rename-object-keys