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

2022-04-07  本文已影响0人  0说
/**
 * 深度合并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
}

上一篇 下一篇

猜你喜欢

热点阅读