美文网首页
2个对象合并成一个对象,且值为后面对象的值

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

作者: 0说 | 来源:发表于2022-04-07 11:09 被阅读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
}

相关文章

网友评论

      本文标题:2个对象合并成一个对象,且值为后面对象的值

      本文链接:https://www.haomeiwen.com/subject/vusjsrtx.html