Deep-convert snake_case and kebab-case keys to camelCase
A backend sends JSON with snake_case and kebab-case keys, but the frontend codebase uses camelCase everywhere. Instead of renaming fields by hand in every API call, the client converts each response once, as soon as it arrives.
Implement camelizeKeys(value). It returns a deep copy of value in which every object key is converted to camelCase.
camelizeKeys(value) // => a converted copy
_ and -. Inside a key, remove each run of one or more separators, and uppercase the character right after it: user_id becomes userId, created-at becomes createdAt, and api__key becomes apiKey._id, __typename, and name_ do not change, and _private_field becomes _privateField.HTTP_status becomes HTTPStatus, and alreadyCamel stays alreadyCamel.line_2_total becomes line2Total.{}, JSON.parse, or Object.create(null)): return a new plain object with converted keys, in the original key order, and converted values.null, undefined, functions, Date, Map, Set, class instances): return it unchanged, as the same reference. String values are never converted, only keys.user_id and userId), throw an Error whose message includes the converted key.camelizeKeys({
order_id: 'A-17',
line_items: [{ sku_code: 'X1', unit_price: 4.5 }],
'shipping-address': { postal_code: '94107' },
__typename: 'Order',
});
// => {
// orderId: 'A-17',
// lineItems: [{ skuCode: 'X1', unitPrice: 4.5 }],
// shippingAddress: { postalCode: '94107' },
// __typename: 'Order',
// }
camelizeKeys({ user_id: 1, userId: 2 });
// throws Error (both keys become 'userId')