| 1 | type SnakeCase<S extends string> = S extends Uppercase<S> ? Lowercase<S> : S extends `${infer P1}${infer P2}` ? P2 extends Uncapitalize<P2> ? `${Lowercase<P1>}${SnakeCase<P2>}` : `${Lowercase<P1>}_${SnakeCase<Uncapitalize<P2>>}` : Lowercase<S>;
|
|---|
| 2 | type NonPlainObject = Date | RegExp | Map<any, any> | Set<any> | WeakMap<any, any> | WeakSet<any> | Promise<any> | Error | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | ((...args: any[]) => any) | typeof globalThis;
|
|---|
| 3 | type ToSnakeCaseKeys<T> = T extends NonPlainObject ? T : T extends any[] ? Array<ToSnakeCaseKeys<T[number]>> : T extends Record<string, any> ? {
|
|---|
| 4 | [K in keyof T as SnakeCase<string & K>]: ToSnakeCaseKeys<T[K]>;
|
|---|
| 5 | } : T;
|
|---|
| 6 | /**
|
|---|
| 7 | * Creates a new object composed of the properties with keys converted to snake_case.
|
|---|
| 8 | *
|
|---|
| 9 | * This function takes an object and returns a new object that includes the same properties,
|
|---|
| 10 | * but with all keys converted to snake_case format.
|
|---|
| 11 | *
|
|---|
| 12 | * @template T - The type of object.
|
|---|
| 13 | * @param {T} obj - The object to convert keys from.
|
|---|
| 14 | * @returns {ToSnakeCaseKeys<T>} A new object with all keys converted to snake_case.
|
|---|
| 15 | *
|
|---|
| 16 | * @example
|
|---|
| 17 | * // Example with objects
|
|---|
| 18 | * const obj = { userId: 1, firstName: 'John' };
|
|---|
| 19 | * const result = toSnakeCaseKeys(obj);
|
|---|
| 20 | * // result will be { user_id: 1, first_name: 'John' }
|
|---|
| 21 | *
|
|---|
| 22 | * // Example with arrays of objects
|
|---|
| 23 | * const arr = [
|
|---|
| 24 | * { userId: 1, firstName: 'John' },
|
|---|
| 25 | * { userId: 2, firstName: 'Jane' }
|
|---|
| 26 | * ];
|
|---|
| 27 | * const arrResult = toSnakeCaseKeys(arr);
|
|---|
| 28 | * // arrResult will be [{ user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }]
|
|---|
| 29 | *
|
|---|
| 30 | * // Example with nested objects
|
|---|
| 31 | * const nested = {
|
|---|
| 32 | * userData: {
|
|---|
| 33 | * userId: 1,
|
|---|
| 34 | * userAddress: {
|
|---|
| 35 | * streetName: 'Main St',
|
|---|
| 36 | * zipCode: '12345'
|
|---|
| 37 | * }
|
|---|
| 38 | * }
|
|---|
| 39 | * };
|
|---|
| 40 | * const nestedResult = toSnakeCaseKeys(nested);
|
|---|
| 41 | * // nestedResult will be:
|
|---|
| 42 | * // {
|
|---|
| 43 | * // user_data: {
|
|---|
| 44 | * // user_id: 1,
|
|---|
| 45 | * // user_address: {
|
|---|
| 46 | * // street_name: 'Main St',
|
|---|
| 47 | * // zip_code: '12345'
|
|---|
| 48 | * // }
|
|---|
| 49 | * // }
|
|---|
| 50 | * // }
|
|---|
| 51 | */
|
|---|
| 52 | declare function toSnakeCaseKeys<T>(obj: T): ToSnakeCaseKeys<T>;
|
|---|
| 53 |
|
|---|
| 54 | export { type ToSnakeCaseKeys, toSnakeCaseKeys };
|
|---|