UNPKG

@modern-kit/utils

Version:
1 lines 2.32 kB
{"version":3,"file":"index.cjs","sources":["../../../src/object/get/index.ts"],"sourcesContent":["import type { PropertyPath, GetByPath } from '@modern-kit/types';\nimport { isNil } from '../../validator/isNil';\n\n/**\n * @description 주어진 객체에서 주어진 경로에 해당하는 값을 반환합니다.\n * 주어진 객체의 타입에 옵셔널 프로퍼티가 있는 경우, 옵셔널(?) 경로로 접근해야 합니다.\n *\n * @template T - 조회하고자 하는 객체 타입\n * @template K - 경로 타입\n *\n * @param {T} obj - 조회하고자 하는 객체\n * @param {K} path - 점 표기법으로 구성된 경로\n * @param {GetByPath<T, K>} defaultValue - 경로에 해당하는 값이 존재하지 않을 경우 반환할 기본값입니다.\n * @returns {GetByPath<T, K>} 경로에 해당하는 값\n *\n * @example\n * const obj: { a: { b: { c: number } } } = { a: { b: { c: 1 } } };\n *\n * get(obj, 'a');\n * // value: { b: { c: 1 } }\n * // type: { b: { c: number } }\n *\n * get(obj, 'a.b');\n * // value: { c: 1 }\n * // type: { c: number }\n *\n * get(obj, 'a.b.c');\n * // value: 1\n * // type: number\n *\n * @example\n * const obj = { a: { b?: { c: 1 } } };\n *\n * get(obj, 'a.b?.c'); // 1, type: 1 | undefined\n * get(obj, 'a.b');\n * // value: { c: 1 }\n * // type: { c: 1 } | undefined\n */\nexport function get<\n T extends Record<PropertyKey, any>,\n K extends PropertyPath<T>\n>(obj: T, path: K, defaultValue?: GetByPath<T, K>): GetByPath<T, K> {\n const paths = path.replace(/\\?/g, '').split('.');\n let result = obj;\n\n for (let i = 0; i < paths.length; i++) {\n const currentPath = paths[i];\n\n if (isNil(result[currentPath])) {\n return defaultValue as GetByPath<T, K>;\n }\n\n result = result[currentPath];\n }\n\n return result as GetByPath<T, K>;\n}\n"],"names":["isNil"],"mappings":";;;;AAsCO,SAAS,GAAA,CAGd,GAAA,EAAQ,IAAA,EAAS,YAAA,EAAiD;AAClE,EAAA,MAAM,QAAQ,IAAA,CAAK,OAAA,CAAQ,OAAO,EAAE,CAAA,CAAE,MAAM,GAAG,CAAA;AAC/C,EAAA,IAAI,MAAA,GAAS,GAAA;AAEb,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAM,WAAA,GAAc,MAAM,CAAC,CAAA;AAE3B,IAAA,IAAIA,oBAAA,CAAM,MAAA,CAAO,WAAW,CAAC,CAAA,EAAG;AAC9B,MAAA,OAAO,YAAA;AAAA,IACT;AAEA,IAAA,MAAA,GAAS,OAAO,WAAW,CAAA;AAAA,EAC7B;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}