对象深度合并方法,类似Object.assign。

index.js

import _assign from './object-assign-deep';

/**
 * 一个或者多个源对象中的属性复制到“目标对象的自有属性”,并“返回修改后的目标对象”。
 * eg: objA = { a: 1, b: 2, c: { num: 99 } }
 *     objB = { b: 4, c: { num: 77, str: 'piter' }}
 *     res = {a: 1, b: 4, c: { num : 77 } }
 * @param {Object} target
 * @param {Boolean} isCloneDeep
 * @param  {...Object} sources
 */
export default function assign(target, isCloneDeep = false, ...sources) {
  if (!isObject(target)) {
    throw new Error('target must be a Object');
  }

  for (const source of sources) {
    if (isObject(source)) {
      _assign(target, source, isCloneDeep);
    }
  }
  return target;
}

object-assign-deep.js

import { cloneDeep } from 'lodash';

/**
 * 对象深度合并,类似Object.assign。
 * @param {Object} target 目标对象
 * @param {Object} source 要拷贝的对象
 * @param {Boolean} isCloneDeep 是否对值深度克隆(针对引用数据类型)
 * @description 仅对源对象已有属性,且属性值为对象的深度合并
 * @returns
 */
export default function _assign(target, source, isCloneDeep = false) {
  // source必须是对象
  if (!isObject(source)) return target;

  const keys = Object.keys(target);
  for (const key of keys) {
    const targetValue = target[key]; // 目标value
    const sourceValue = source?.[key]; // 将合并的value

    // 如果targetValue是对象,继续深度赋值
    if (isObject(targetValue)) {
      _assign(targetValue, sourceValue);
    } else if (Object.hasOwnProperty.call(source, key)) {
      // 如果targetValue不是对象,且source存在此Key
      target[key] = isCloneDeep ? cloneDeep(sourceValue) : sourceValue;
    }
  }
  return target;
}

isObject.js

export default function isObject(target) {
  return {}.toString.call(target) === '[object Object]';
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值