30 Seconds of Code: How to rename multiple object keys in JavaScript
30 Seconds of Code is a brilliant collection of JavaScript snippets, digestible in ≤ 30 seconds. Anyone looking to master JavaScript should go through the entire thing.
The list didn’t contain a function to rename multiple object keys, however, so I created a pull request that thankfully got merged!
Here’s the official entry: https://30secondsofcode.org/object#renamekeys
I’ve previously written on renaming object keys, but we only changed one key at a time.
Then Adam Rowe kindly commented, asking how we might rename multiple object keys. I replied with this code sample after some thought and research.
renameKeys = (keysMap, obj) => Object
.keys(obj)
.reduce((acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] }
}), {});
This was inspired by Ramda Adjunct’s renameKeys
function.
keysMap
contains key/value pairs of your old/new object keys.obj
is the object to be changed.
You might use it like this:
keysMap = {
name: 'firstName',
job: 'passion'
};obj = {
name: 'Bobo',
job: 'Front-End Master'
};