数组里面数据分组排序

转换前数据

[{
    "type": "A",
    "month": "2019-03",
    "amount": 200,
    "username": "a001"
  },
  {
    "type": "A",
    "month": "2019-03",
    "amount": 1200,
    "username": "a002"
  }
  {
    "type": "A",
    "month": "2019-02",
    "amount": 300,
    "username": "a001"
  }
  {
    "type": "B",
    "month": "2019-02",
    "amount": 200,
    "username": "b001"
  },
  {
    "type": "C",
    "month": "2019-03",
    "amount": 200,
    "username": "c001"
  }
]

转换后数据

[
  {
    "month": "2019-02",
    "list": [{
      "type": "A",
      "info": [{
        "amount": 300,
        "username": "a001"
      }]
    },{
      "type": "B",
      "info": [{
        "amount": 200,
        "username": "b001"
      }]
    }]
  },{
    "month": "2019-03",
    "list": [{
      "type": "A",
      "info": [{
        "amount": 1200,
        "username": "a002"
      },{
        "amount": 200,
        "username": "a001"
      }]
    },{
      "type": "C",
      "info": [{
        "amount": 200,
        "username": "c001"
      }] 
    }
  }
]

实现如下:

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}
const groups = groupBy(arr,'month');
const final = Object.entries(groups).map(([month,e]) => {
  return {
    month,
    list: Object.entries(groupBy(e,'type')).map(([type,el]) => ({
      info: el,
      type
    }))
  }
})
console.log(final)
posted @ 2019-03-11 17:55  曾志呀  阅读(691)  评论(0编辑  收藏  举报