小程式 - 陣列匹配

青呢喃發表於2018-08-27

根據2個陣列的唯一id:playSign,將其中一個陣列的值匹配到另一個陣列中

  • 二維陣列
    activityInfo: [
      {
        categoryName:'類名1',
        brefInfoDtos:[
          { activityId: 1, activityName: "活動1", playSign: 1, imgUrl: ""},
          { activityId:2, activityName: "活動2", playSign:2, imgUrl: "" },
        ]
      },
      {
        categoryName: '類名2',
        brefInfoDtos: [
          { activityId: 1, activityName: "活動1", playSign: 1, imgUrl: "" },
          { activityId: 2, activityName: "活動3", playSign: 2, imgUrl: "" },
        ]
      }
    ]
    
複製程式碼
  • 陣列二
list: [
      {
        playSign:1,
        name: '幸運九宮格',
        url: 'pages/jiugongge/jiugongge'
      }, {
        playSign:2,
        name: '刮刮樂',
        url: 'pages/guaguale/guaguale'
      }
    ]
複製程式碼

二維陣列迴圈,根據playSign的id篩選出陣列2的url,然後追加到陣列1中.

程式碼

  onLoad: function (options) {
    var that = this;
    //請求到商家活動資訊
      if (that.data.activityInfo.length > 0) {
        var newArr = that.data.activityInfo;
        newArr.forEach(function (value, index) {
          value.brefInfoDtos.forEach(function (value, index) {
            var url = that.data.list.filter(v => {
              if (value.playSign == v.playSign) {
                return v;
              }
            })
            value.url = url[0].url;
          })
        })
        that.setData({
          'activityInfo': newArr
        })
      }
  },
複製程式碼

相關文章