如何使用lodash按国家、品牌双属性分组订单数组统计各状态数量
订单按国家+品牌维度分组统计实现方案
原有方案的核心问题是没有处理单订单多品牌的归属逻辑:单个订单包含多个品牌时,该订单需要同时计入所属国家下每个关联品牌的统计,不能直接按整单做单维度归组。
实现逻辑
- 先拆分多品牌订单,把每个订单按关联品牌展开为「国家-品牌-订单状态」的最小统计单元
- 以「国家+品牌」为组合维度做分组
- 对每个分组下的订单按状态计数,输出符合要求的结构
完整代码(Lodash版,可直接在Vue组件中使用)
import _ from 'lodash' // 项目内定义的订单状态枚举,保持和原有业务逻辑一致 const SFCC_STATUS = { new: 'new', open: 'open', completed: 'completed', pending: 'pending', paid: 'paid' // 其余状态可按需补充 } const calOrderGroupStats = (orderList) => { // 1. 拆分多品牌订单,生成最小统计单元 const flatItems = [] orderList.forEach(order => { const country = order.base.country const currentStatus = order.base.status // 遍历订单下所有品牌,每个品牌都要计入当前订单的统计 order.base.brands.forEach(brand => { flatItems.push({ country, brand, status: currentStatus }) }) }) // 2. 按国家+品牌组合维度分组,用双下划线做分隔避免key冲突 const groupedMap = _.groupBy(flatItems, item => `${item.country}__${item.brand}`) // 3. 逐组统计各状态订单数 const statResult = [] Object.values(groupedMap).forEach(group => { const { country, brand } = group[0] // 若需要固定返回所有状态字段(计数为0也返回),可打开下方注释初始化所有状态 // const currentStat = { country, brand, ...Object.fromEntries(Object.values(SFCC_STATUS).map(s => [s, 0])) } const currentStat = { country, brand } group.forEach(item => { currentStat[item.status] = (currentStat[item.status] || 0) + 1 }) statResult.push(currentStat) }) return statResult } // 组件内调用方式 // const table = calOrderGroupStats(orders.value)
示例效果
传入你提供的测试订单数据:
[{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":"new"}},{"id":"DEC-00500331","base":{"brands":["DEC"],"country":"UK","status":"new"},"psp":{"name":"adyen","status":"paid"}}]
返回结果如下:
[ { "country": "BG", "brand": "KI", "new": 1 }, { "country": "BG", "brand": "SA", "new": 1 }, { "country": "UK", "brand": "DEC", "new": 1 } ]
适配说明
- 如果需要统计支付状态(即
psp.status字段),只需在生成最小统计单元时,把status的取值改为order.psp?.status,做好空值兼容即可 - 如果需要过滤特定状态的订单,在遍历生成
flatItems阶段加判断过滤即可,比分组后再过滤性能更好
内容的提问来源于stack exchange,提问作者k.h.t
相关产品推荐
相关产品推荐

