feat: 工具函数getNestPrperty用于扁平化对象
This commit is contained in:
44
src/helper/nest.ts
Normal file
44
src/helper/nest.ts
Normal file
@ -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<T>(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<string, unknown>)[key];
|
||||
return dive(value, index + 1);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const result = dive(obj, 0);
|
||||
return result as T | T[] | undefined;
|
||||
}
|
||||
Reference in New Issue
Block a user