es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

Support toSnakeObject

Open gweesin opened this issue 8 months ago • 0 comments

can convert all of keys to snake, for example:

import { snakeCase, isPlainObject, isNil } from 'es-toolkit';

/**
 * @param {Record<string, any>|Array<Record<string, any>>} obj
 * @return {Record<string, any>}
 */
export function toSnakeObject(obj) {
    if (Array.isArray(obj)) {
        return obj.map(toSnakeObject);
    }

    if (isNil(obj)) {
        return {};
    }

    return Object.keys(obj).reduce((acc, key) => {
        const value = obj[key];
        if (isPlainObject(value)) {
            acc[snakeCase(key)] = toSnakeObject(value);
        } else {
            acc[snakeCase(key)] = value;
        }

        return acc;
    }, {});
}

toSnakeObject({ camelCase: 1, phoneNumber: 10086 }); // { camel_case: 1, phone_number: 10086 }

gweesin avatar Feb 28 '25 06:02 gweesin