2个对象合并成一个对象,且值为后面对象的值

/**
 * 深度合并2个对象
 * @param {*} target
 * @param {*} other
 */
 export const deepMerge = (target, other) => {
  const targetConstructorType = target.constructor
  const otherConstructorType = other.constructor
  if (targetConstructorType === Object && otherConstructorType === Object) {
      for (const [key, val] of Object.entries(other)) {
        if (target[key] && typeof target[key] === 'object') {
          target[key] = deepMerge(target[key], val)
        } else {
          target[key] = val
        }
      }
  } else if (targetConstructorType === Array && otherConstructorType === Array) {
      for (const [key, val] of Object.entries(other)) {
        if (target[key]) {
          target[key] = deepMerge(target[key], val)
        } else {
          target.push(val)
        }
      }
  } else {
    target = other
  }
  return target
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容