Last active
August 6, 2019 06:43
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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