Immutably rename object keys
Return a copy with keys renamed through a mapping.
function renameKeys({ keysMap, object }) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [keysMap[key] || key, value])); }
Input & expected output
Input
{
"keysMap": {
"idempotency_key": "idempotencyKey"
},
"object": {
"to": "[email protected]",
"idempotency_key": "order-confirmation:8812:1"
}
}Expected output
{
"to": "[email protected]",
"idempotencyKey": "order-confirmation:8812:1"
}The edge case
Input
{
"keysMap": {},
"object": {}
}Expected output
{}Know the limits
- Object.fromEntries replaces the original reduce with spread, which copied the accumulator on every key.
- If two keys map to the same name, the later one wins.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Immutably rename object keys from the original 1loc collection by Nguyen Huu Phuoc, with imyangyong. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses Object.fromEntries instead of spreading the accumulator for every key. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Pick properties from an object — Build a new object with only the requested own properties.
- Omit properties from an object — Keep the own enumerable fields that are not in a supplied list.
- Create an object from pairs of key and value — Turn [key, value] pairs into a plain object with Object.fromEntries.