diff --git a/src/helper/nest.ts b/src/helper/nest.ts new file mode 100644 index 0000000..e767ec8 --- /dev/null +++ b/src/helper/nest.ts @@ -0,0 +1,44 @@ +/** + * 获取 obj 中路径 path 对应的值。 + * 支持路径中的数组:如果在前一层得到数组,则对该数组中每个元素进一步取值。 + * @param obj 任意对象或数组 + * @param path 点分隔路径(例如 "a.b.c" 或 "translations.name") + * @returns 如果结果仅一个值,返回该值;如果多个,返回值数组;如果无值,返回 undefined。 + * + * --- + * @example + * const data = { + * translations: [ + * { languages_code: 'zh-CN', name: '中文' }, + * { languages_code: 'en-US', name: 'English' } + * ] + * }; + * + * getNestedProperty(data, 'translations.name'); + * // 返回 ['中文', 'English'] + */ +export function getNestedProperty(obj: unknown, path: string): T | T[] | undefined { + const parts = path.split('.'); + + function dive(current: unknown, index: number): unknown { + if (current == null) return undefined; + if (index >= parts.length) return current; + + const key = parts[index]; + if (!key) return undefined; + + if (Array.isArray(current)) { + return current.map((item) => dive(item, index)); + } + + if (typeof current === 'object') { + const value = (current as Record)[key]; + return dive(value, index + 1); + } + + return undefined; + } + + const result = dive(obj, 0); + return result as T | T[] | undefined; +} \ No newline at end of file