Last active
October 1, 2021 20:33
-
-
Save lockdef/d0a42bb741ae2a60bd4283bfc0255941 to your computer and use it in GitHub Desktop.
オブジェクトのキーをキャメルケースtoスネークケースまたはスネークケースtoキャメルケースに変換する便利関数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type obj = { | |
| [key: string]: any | |
| } | |
| const typeOf = (obj: any): string => { | |
| return toString.call(obj).slice(8, -1).toLowerCase() | |
| } | |
| const camelToSnakeArray = (arr: any[]): any[] => { | |
| return arr.map((item: any) => { | |
| if (typeOf(item) === 'object') return camelToSnakeObject(item) | |
| if (typeOf(item) === 'array') return camelToSnakeArray(item) | |
| return item | |
| }) | |
| } | |
| const camelToSnakeObject = (obj: obj): obj => { | |
| const result: obj = {} | |
| Object.keys(obj).forEach((key) => { | |
| result[key.replace(/([A-Z])/g, '_$1').toLowerCase()] = (() => { | |
| if (typeOf(obj[key]) === 'object') return camelToSnakeObject(obj[key]) | |
| if (typeOf(obj[key]) === 'array') return camelToSnakeArray(obj[key]) | |
| return obj[key] | |
| })() | |
| }) | |
| return result | |
| } | |
| const snakeToCamelArray = (arr: any[]): any[] => { | |
| return arr.map((item: any) => { | |
| if (typeOf(item) === 'object') return snakeToCamelObject(item) | |
| if (typeOf(item) === 'array') return snakeToCamelArray(item) | |
| return item | |
| }) | |
| } | |
| const snakeToCamelObject = (obj: obj): obj => { | |
| const result: obj = {} | |
| Object.keys(obj).forEach((key) => { | |
| result[key.replace(/_(\w)/g, (_, p1) => p1.toUpperCase())] = (() => { | |
| if (typeOf(obj[key]) === 'object') return snakeToCamelObject(obj[key]) | |
| if (typeOf(obj[key]) === 'array') return snakeToCamelArray(obj[key]) | |
| return obj[key] | |
| })() | |
| }) | |
| return result | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment