UNPKG

@tienedev/datype

Version:

Modern TypeScript utility library with pragmatic typing and zero dependencies

93 lines 2.76 kB
/** * Transform all keys in an object using an iterator function while preserving the values. * Returns a new object with transformed keys and the same values. * * @template T - The type of the input object * @template K - The type of the new keys * @param obj - The object to transform * @param iteratee - Function that transforms each key * @returns A new object with transformed keys * * @example * ```typescript * import { mapKeys } from 'datype'; * * // Transform to camelCase * const apiData = { * 'first_name': 'John', * 'last_name': 'Doe', * 'email_address': 'john@example.com' * }; * * const camelCase = mapKeys(apiData, key => * key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) * ); * // { firstName: 'John', lastName: 'Doe', emailAddress: 'john@example.com' } * * // Add prefix to keys * const data = { name: 'John', age: 30 }; * const prefixed = mapKeys(data, key => `user_${key}`); * // { user_name: 'John', user_age: 30 } * * // Transform based on value * const config = { * apiUrl: 'https://api.example.com', * timeout: 5000, * retries: 3 * }; * * const withTypes = mapKeys(config, (key, value) => { * const type = typeof value === 'string' ? 'str' : 'num'; * return `${type}_${key}`; * }); * // { str_apiUrl: 'https://api.example.com', num_timeout: 5000, num_retries: 3 } * * // Normalize keys * const messyData = { * 'First Name': 'John', * 'LAST_NAME': 'Doe', * 'Email-Address': 'john@example.com' * }; * * const normalized = mapKeys(messyData, key => * key.toLowerCase().replace(/[-\s]/g, '_') * ); * // { first_name: 'John', last_name: 'Doe', email_address: 'john@example.com' } * ``` */ export declare function mapKeys<T extends Record<PropertyKey, any>, K extends PropertyKey>(obj: T, iteratee: (key: keyof T, value: T[keyof T], object: T) => K): Record<K, T[keyof T]>; export declare const keyTransformers: { /** * Convert snake_case to camelCase */ toCamelCase: (key: string) => string; /** * Convert camelCase to snake_case */ toSnakeCase: (key: string) => string; /** * Convert to kebab-case */ toKebabCase: (key: string) => string; /** * Convert to lowercase */ toLowerCase: (key: string) => string; /** * Convert to uppercase */ toUpperCase: (key: string) => string; /** * Add prefix to key */ addPrefix: (prefix: string) => (key: string) => string; /** * Add suffix to key */ addSuffix: (suffix: string) => (key: string) => string; /** * Normalize key by removing special characters and converting to snake_case */ normalize: (key: string) => string; }; //# sourceMappingURL=index.d.ts.map