js 對象深拷貝 合併對象

deepMerge(...objs) {
      const result = Object.create(null)
      objs.forEach(obj => {
        if (obj) {
          Object.keys(obj).forEach(key => {
            const val = obj[key]
            if (isPlainObject(val)) {
              // 遞歸
              if (isPlainObject(result[key])) {
                result[key] = deepMerge(result[key], val)
              } else {
                result[key] = deepMerge(val)
              }
            } else {
                //  數組也要重新賦值  不然依然會引用到其他的
              if (Array.isArray(val)) {
                result[key] = [...val]
              } else {
                result[key] = val
              }
            }
          })
        }
      })
      console.log(result)
      return result
    }


    isPlainObject(val) {
      const toString = Object.prototype.toString
      return toString.call(val) === '[object Object]'
    }

deepMerge 參數,後面對象會覆蓋前面的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章