training_data/packages/utils/src/object-utils.ts

60 lines
1.8 KiB
TypeScript
Executable File

// 优雅实现对象操作工具函数集合
/**
* 深拷贝对象或数组
* @param input 需要深拷贝的对象或数组
* @returns 深拷贝后的新对象/数组
*/
export function deepClone<T>(input: T): T {
if (input === null || typeof input !== 'object') return input;
if (Array.isArray(input)) return input.map(deepClone) as unknown as T;
const result = {} as T;
for (const key in input) {
if (Object.prototype.hasOwnProperty.call(input, key)) {
result[key] = deepClone(input[key]);
}
}
return result;
}
/**
* 合并多个对象
* @param objects 需要合并的对象列表
* @returns 合并后的对象
*/
export function mergeObjects<T>(...objects: Partial<T>[]): T {
return objects.reduce((acc: Partial<T>, obj) => {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (typeof acc[key] === 'object' && typeof obj[key] === 'object') {
acc[key] = mergeObjects(acc[key], obj[key]);
} else {
acc[key] = obj[key];
}
}
}
return acc;
}, {} as Partial<T>) as T;
}
/**
* 获取嵌套对象的属性值
* @param obj 待操作对象
* @param path 属性路径(以点分隔)
* @param defaultValue 默认值
* @returns 属性值或默认值
*/
export function getNestedValue<T, U>(obj: T, path: string, defaultValue: U): U | unknown {
return path.split('.').reduce((acc: any, key: string) => acc && acc[key], obj) ?? defaultValue;
}
/**
* 判断对象是否为空
* @param obj 待检查对象
* @returns 是否为空对象
*/
export function isEmptyObject(obj: Record<string, unknown>): boolean {
return Object.keys(obj).length === 0;
}