How To Rename Multiple Keys In A JavaScript Object
Renaming the keys in a Javascript (or JSON) object can be quite tricky, this is a simple trick to rename all the keys you want.
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
.
renameKeys({ name: "firstName", age: "lifeExperience" }, person);
The new person object will now have updated keys.