Files
30-seconds-of-code/snippets/rename-keys.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

762 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Rename object keys object fallen-leaves 2018-04-10T20:22:39+03:00 2020-10-22T20:24:30+03:00

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 }