比如一个数据如下
根据shop_id 相同 进行分组
- let orders = []
- goods.forEach((item, index) => {
- let has = orders.findIndex(o => o.shop_id === item.shop_id)
- if(has == -1) {
- orders.push({
- shop_id: item.shop_id,
- goods: [item]
- })
- } else {
- orders[has].goods.push(item)
- }
- })
得到的结果是
还可以按照shop_id计算出 goods数组中总数量 和 总金额
- orders.forEach((item, index) => {
- orders[index].order_price = item.goods.reduce((total, v) => total += v.sell_number * v.price, 0)
- orders[index].order_number = item.goods.reduce((num, v) => num += v.sell_number, 0)
- })