How To Rename Multiple Keys In A JavaScript Object
2 min read

Renaming Keys

This function will help you rename the keys of an existing object, it is based on the use of Object.keys() in a combination with Array.prototype.reduce(). This function is originally from this website.

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

Usage

Let’s use a basic example and how we can rename it. We have this object with some basic values.

const person = { name: "Joe", gender: "Male", age: 30 };

We want to rename name to firstName and age to lifeExperience.

const updated = renameKeys({ name: "firstName", age: "lifeExperience" }, person);
// {firstName: 'Joe', gender: 'Male', lifeExperience: 30}

The new person object will now have updated keys.