Skip to content

Instantly share code, notes, and snippets.

@loopmode
Last active August 6, 2019 06:43
Show Gist options
  • Save loopmode/e41f127a3b22af7193dd060c8944d5eb to your computer and use it in GitHub Desktop.
Save loopmode/e41f127a3b22af7193dd060c8944d5eb to your computer and use it in GitHub Desktop.
A JS function for renaming properties of an object while maintaining the original iteration order
export function renameObjKeys(obj, mapping) {
// based on https://stackoverflow.com/a/48110891/368254
const renameObjKey = (obj, { oldKey, newKey }) => {
const keys = Object.keys(obj);
const newObj = keys.reduce((acc, val) => {
if (val === oldKey) {
acc[newKey] = obj[oldKey];
} else {
acc[val] = obj[val];
}
return acc;
}, {});
return newObj;
};
return Object.entries(mapping).reduce((result, [oldKey, newKey]) => {
return renameObjKey(result, { oldKey, newKey });
}, obj);
}
const oldObj = {
'/': {
label: 'Home'
},
'/users': {
label: 'Users'
},
'/admin': {
label: 'Admin'
}
}
console.log(Object.keys(oldObj)); // ['/', '/users', '/admin']
const newObj = renameObjKeys(oldObj, {'/': '/home', '/admin': '/foo'});
console.log(Object.keys(newObj)); // ['/home', '/users', '/foo']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment