Wechat applet: add a new field [key, value] to the array returned in the background

Posted by mcerveni on Tue, 26 Nov 2019 17:23:07 +0100

Wechat applet: add a new field [key, value] to the array returned in the background

1. Business requirements

Request a to return all the vehicle information to me, receive it with an array of cars, traverse the array to get the license plate number, and send b request to query whether to open wechat owner service every time I get a license plate number, and use new fields to receive the vehicle status, and then put the new fields into cars, and the page renders data.

2. effect picture


3. Implementation method 1: directly give the array cars: status + attribute value

Problem: for loop nesting http request, asynchronous callback, request interruption, all changed to the status of the last vehicle
selectCar:function(){
    var ts = this
    e.request('/v1/associators?Corporation=park&openid=' + wx.getStorageSync('openid'),
      {}, 'GET').then((res) => {
        console.log(res)
        if (res.statusCode == '200' && res.data.list[0].car_parks) {
          ts.setData({cars:res.data.list[0].car_parks,show:true})
          console.log(ts.data.cars)
          var modal = ts.data.cars
          for (var index in modal){
            e.request('/managementchanel/querystate?', { usr_num: modal[index].platecard}, 'POST').then((res) => {
                console.log("444")
                if (res.data.path != '') {
                  modal[index].status = false
                console.log(ts.data.cars[index])
                }else{
                  modal[index].status = true
                }
              })
          }
          ts.setData({
            cars: modal
          })
          console.log("1111")
          console.log(ts.data.cars)
        }else{
          ts.setData({show: false})
        }
      })
  },

4. Implementation mode 2 (recommended): use object to receive status

selectCar: function() {
    var ts = this
    e.request(url, {}, 'GET').then((res) => {
      console.log(res)
      if (res.statusCode == '200' && res.data.list[0].car_parks) {
        ts.setData({
          cars: res.data.list[0].car_parks,//Receive vehicle list with cars
          show: true
        })
        for (let index in ts.data.cars) {
          let obj = {}
          let obj1 = ts.data.cars[index]
          e.request('/managementchanel/querystate?', {
            usr_num: ts.data.cars[index].platecard
          }, 'POST').then((res) => {
            if (res.data.path != '') {
              obj1.status = false
            } else {
              obj1.status = true
            }
            obj['cars[' + index + ']'] = obj1
            console.log(obj)
            ts.setData(obj)
          })
        }
        console.log("1111")
        console.log(ts.data.cars)
      } else {
        ts.setData({
          show: false
        })
      }
    })
  },

Topics: Attribute