美文网首页
数组中把相同键值相同的数据提取出来合并,并且放到一个新的数组里面

数组中把相同键值相同的数据提取出来合并,并且放到一个新的数组里面

作者: 读书的鱼 | 来源:发表于2019-04-09 12:28 被阅读0次
    //原始数据
    const data = [{
        id: 1,
       address: '河北邯郸',
       businessId: 1001,
       businessType: '审核中'
    },{
        id: 2,
       address: '河北沧州',
       businessId: 1002,
       businessType: '审核中'
    },{
        id: 3,
       address: '河北廊坊',
       businessId: 1003,
       businessType: '审核通过'
    },{
        id: 3,
       address: '河北张家口',
       businessId: 1004,
       businessType: '审核通过'
    }]
    //方法
    function arrayTransfer(data){
      const listArr = [];
      data.forEach(function(el){
          for(let i = 0;i < listArr.length; i++){
            if(listArr[i].businessType === el.businessType){
              listArr[i].listInfo.push({
                  id: el.id,
                  address: el.address,
                  businessId: el.businessId,
                  businessType: el.businessType
              });
              return;
            }
          }
    
          listArr.push({
            businessType: el.businessType,
            listInfo:[{
               id: el.id,
               address: el.address,
               businessId: el.businessId,
               businessType: el.businessType
            }]
          })
      })
      return listArr
    }
    
    //我们想要的数据
    data = [{
      businessType: '审核中',
      listInfo:[{
          id: 1,
          address: '河北邯郸',
          businessId: 1001,
          businessType: '审核中'
      },{
          id: 2,
         address: '河北沧州',
         businessId: 1002,
         businessType: '审核中'
      }]
    },{
      businessType: '审核通过',
      listInfo: [{
          id: 3,
         address: '河北廊坊',
         businessId: 1003,
         businessType: '审核通过'
       },{
          id: 3,
         address: '河北张家口',
         businessId: 1004,
         businessType: '审核通过'
      }]
    }]
    

    相关文章

      网友评论

          本文标题:数组中把相同键值相同的数据提取出来合并,并且放到一个新的数组里面

          本文链接:https://www.haomeiwen.com/subject/ooieeqtx.html