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
}

你可能感兴趣的:(2个对象合并成一个对象,且值为后面对象的值)