Skip to content

Instantly share code, notes, and snippets.

@maggiben
Created October 4, 2021 18:49
Show Gist options
  • Save maggiben/91a0e9e90144df11e6146632390c7967 to your computer and use it in GitHub Desktop.
Save maggiben/91a0e9e90144df11e6146632390c7967 to your computer and use it in GitHub Desktop.
A recursive function to map an object keys
import { isPlainObject } from '@salesforce/ts-types';
/**
* Use mapKeys to convert object keys to another format using the specified conversion function.
*
* E.g., to deep convert all object keys to camelCase: mapKeys(myObj, _.camelCase, true)
* to shallow convert object keys to lower case: mapKeys(myObj, _.toLower)
*
* NOTE: This mutates the object passed in for conversion.
*
* @param target - {Object} The object to convert the keys
* @param converter - {Function} The function that converts the object key
* @param deep - {boolean} Whether to do a deep object key conversion
* @return {Object} - the object with the converted keys
*/
export default function mapKeys(
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
obj: any,
converter: (key: string) => string,
deep?: boolean
): Record<string, unknown> {
const target = Object.assign({}, obj);
return Object.fromEntries(
Object.entries(target).map(([key, value]) => {
const k = converter.call(null, key);
if (deep) {
let v = value;
if (Array.isArray(value)) {
v = value.map((v1) => {
if (isPlainObject(v1)) {
return mapKeys(v1, converter, deep);
}
return v1;
});
} else if (isPlainObject(value)) {
v = mapKeys(value, converter, deep);
}
return [k, v];
}
return [k, value];
})
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment