| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- /**
- * 对象浅拷贝
- * @param target 目标对象
- * @param source 源对象
- * @returns
- */
- export function merge<T>(target: T, ...source: T[]): T {
- source.forEach((e) => {
- for (const key in e) {
- if (Object.prototype.hasOwnProperty.call(target, key)) {
- target[key] = e[key];
- }
- }
- })
- return target;
- }
- /**
- * 对象深拷贝
- * @param target 目标对象
- * @param source 源对象
- * @returns
- */
- export function deepMerge<T>(target: T, source: T): T {
- for (const key in source) {
- // 判断属性是否存在
- if (Object.prototype.hasOwnProperty.call(target, key)) {
- const t = target[key];
- const s = source[key];
- // 对象属性类型检查
- switch (Object.prototype.toString.call(t)) {
- case '[object Object]':
- target[key] = deepMerge(t, s);
- break;
- case '[object Array]':
- if (Array.isArray(t) && Array.isArray(s)) {
- target[key] = t.reduce((prev, cur, i) => {
- const value = deepMerge(cur, s[i]);
- prev.push(value);
- return prev;
- }, [])
- }
- break;
- default:
- target[key] = s;
- }
- }
- }
- return target;
- }
|