import * as type from './type'; /** * target与sources合并 * @param target * @param sources * @returns 合并后的对象 */ export function merge(target: object, ...sources: any[]) { if (!sources?.length) return target; const mergeOne = (target, source) => { if (!source) return target; const phantomTarget = cloneDeep(target); Object.entries(source).forEach(([key, value]) => { if (Array.isArray(value)) { if (!phantomTarget[key] || !Array.isArray(phantomTarget[key])) { phantomTarget[key] = value; } else { phantomTarget[key] = Array.from(new Set([...value])); } } else if (type.isObject(value)) { phantomTarget[key] = mergeOne(phantomTarget[key] ? phantomTarget[key] : phantomTarget[key] = {}, value); } else { phantomTarget[key] = value; } }); return phantomTarget; }; const source = sources.reduce((memo, current) => mergeOne(memo, current), {}); return mergeOne(target, source); } export function cloneDeep(data) { let result; if (Array.isArray(data)) { result = []; } else if (type.isObject(data)) { result = {}; } else { return data; } if (Array.isArray(data)) { data.forEach((item) => { result.push(cloneDeep(item)); }); return result; } if (type.isObject(data)) { Object.entries(data).forEach(([key, value]) => { result[key] = cloneDeep(value); }); return result; } }