数据拷贝

在工作的时候, 项目的某些页面总是会因为数据的缺失而导致报错, 刚开始用的一个一个添加的方法, 但是因为后来新增的字段增多, 逐个添加的方法增加代码量,还麻烦,就自己写了一个补全数据的方法.具体代码如下:

// 判断数据类型, 该方法(constructor)在传入null和undefined是会报错,所以要去除
      constructorJudge(val) {
        if (val === null || val === undefined) {
          return false
        }
        const options = val
        let dataType
        switch (options.constructor) {
          case String:
            dataType = 'String'
            break;
          case Number:
            dataType = 'Number'
            break;
          case Boolean:
            dataType = 'Boolean'
            break;
          case Function:
            dataType = 'Function'
            break;
          case Date:
            dataType = 'Date'
            break;
          case Array:
            dataType = 'Array'
            break;
          case Object:
            dataType = 'Object'
            break;
          default:
            break;
        }
        return dataType
      },


      // 遍历数组,补全数据,  第一个参数为完整的数据, 第二个参数为有缺失的数据
      supplementData(fullData, deficiencyData) {
        const fullObj = fullData        	    // 完整的数据
        const deficiencyObj = deficiencyData    // 有部分缺失的数据
        if (this.constructorJudge(fullObj) === 'Object' && this.constructorJudge(deficiencyObj) === 'Object') {
          const fullObjkeys = Object.keys(fullObj)
          fullObjkeys.forEach((item) => {
            // 对象中不存在的属性, 添加上
            if (!deficiencyObj.hasOwnProperty(item)) {
              deficiencyObj[item] = fullObj[item]
            // 如果是对象的话,递归
            } else if (deficiencyObj.hasOwnProperty(item) && (this.constructorJudge(fullObj[item]) === 'Object')) {
              if (this.constructorJudge(deficiencyObj[item]) !== 'Object') {
                deficiencyObj[item] = fullObj[item]
              } else {
                this.supplementData(fullObj[item], deficiencyObj[item])
              }
            // 如果是数组的话,循环数组,递归
            } else if (deficiencyObj.hasOwnProperty(item) && (this.constructorJudge(fullObj[item]) === 'Array')) {
              if (this.constructorJudge(deficiencyObj[item]) !== 'Array') {
                deficiencyObj[item] = fullObj[item]
              } else {
                const arr = deficiencyObj[item]
                // console.log(item, arr)
                if (arr.length === 0) {
                  deficiencyObj[item] = fullObj[item]
                } else {
                  arr.forEach((itemArr) => {
                    this.supplementData(fullObj[item][0], itemArr)
                  })
                }
              }
            }
          })
        }
        return deficiencyData
      },
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值