JS 数组对象的某一项抽离出来放在外面

数组类型:

shamDeviceData: [
        {
          "projectKey":"5555",
          "productKey":"55555555",
          "deviceId":"555555555",
          "deviceName":"55555555",
          "imei":"5555555",
          "devReturnAlarmList":[{
            "statusCode":"55555",
            "statusValue":"5555",
            "alarmDesc":"5555",
            "alarmType": '1'
          }]
        },
        {
          "projectKey":"6666666",
          "productKey":"6666",
          "deviceId":"6666",
          "deviceName":"helo",
          "imei":"how are you",
          "devReturnAlarmList":[
            {
              "statusCode":"6666",
              "statusValue":"6666",
              "alarmDesc":"8888888",
              "alarmType": '1'
            },
            {
              "statusCode":"67677677",
              "statusValue":"676767",
              "alarmDesc":"99999",
              "alarmType": '1'
            },
            {
              "statusCode":"67677677",
              "statusValue":"676767",
              "alarmDesc":"tttttttt",
              "alarmType": '1'
            }
          ]
        },
        {
          "projectKey":"777777",
          "productKey":"777777",
          "deviceId":"77777",
          "deviceName":"77777",
          "imei":"77777",
          "devReturnAlarmList":[]
        }
      ],

思路:

1. 把 devReturnAlarmList 数组里面的每一项拿到外面来,重新生成一个新数组,如果devReturnAlarmList有多项,则生成多个数组

2. 合并新对象  { }一定要写

Object.assign({},item, item.devReturnAlarmList[num])

解决:

this.shamDeviceData.forEach((item,i) => {
            if (item.devReturnAlarmList.length) {
              if (item.devReturnAlarmList.length) {
                for (let i = 0; i < item.devReturnAlarmList.length; i++) {
                  (function(num) {
                    _this.handleShamDeviceData.push(Object.assign({},item, item.devReturnAlarmList[num]))  // 这里一定要注意,拼接成新对象{},不然item.devReturnAlarmList[num]始终取的是最后一个值,闭包没生效
                  })(i)
                }
              }
            } else {
              this.handleShamDeviceData.push(item)
            }
          })
          console.log(this.handleShamDeviceData)

 

打印的 handleShamDeviceData 如下:

 

 

 

posted @ 2019-10-16 17:14  front-gl  阅读(2684)  评论(0编辑  收藏  举报