Files
30-seconds-of-code/snippets/renameKeys.md
30secondsofcode bac7270495 Travis build: 1951
2018-04-12 18:45:32 +00:00

621 B

renameKeys

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

Use Object.keys() in combination with Array.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 }