← 中文资源

简体中文版本

Object.groupBy 拆分计数与合计

Object.groupBy 把记录装进无原型桶,再从桶里派生计数、组内金额合计;缺失桶读出来是 undefined,访问前先判断存在。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

regions : [ 'eu', 'us', 'apac' ]
eu      : [ 'o-1', 'o-3' ]
tally   : { eu: 2, us: 2, apac: 1 }
totals  : [
  { region: 'eu', cents: 2000 },
  { region: 'us', cents: 7200 },
  { region: 'apac', cents: 3200 }
]
missing : no bucket

实现说明

各个操作都建立在顶层绑定之上:orders、byRegion、tally、totals。

使用要点

  • 演示输出是带标签的(regions :、missing :),每个操作都会留下自己的一行标注。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 跨调用保留的状态放在这些顶层绑定里:orders、byRegion、tally。

核心语句

const totals = Object.entries(byRegion).map(([region, group]) => ({
  region,
  cents: group.reduce((sum, o) => sum + o.cents, 0),
}));
const byRegion = Object.groupBy(orders, (o) => o.region);

代码示例

const orders = [
  { id: 'o-1', region: 'eu', cents: 1200 },
  { id: 'o-2', region: 'us', cents: 4500 },
  { id: 'o-3', region: 'eu', cents: 800 },
  { id: 'o-4', region: 'apac', cents: 3200 },
  { id: 'o-5', region: 'us', cents: 2700 },
];

const byRegion = Object.groupBy(orders, (o) => o.region);
console.log('regions :', Object.keys(byRegion));
console.log('eu      :', byRegion.eu.map((o) => o.id));

// 计数是聚合而不是分组:对每个桶数一次长度
const tally = Object.fromEntries(
  Object.entries(byRegion).map(([region, group]) => [region, group.length]),
);
console.log('tally   :', tally);

// 每个桶做组内聚合:region 的金额合计来自 reduce
const totals = Object.entries(byRegion).map(([region, group]) => ({
  region,
  cents: group.reduce((sum, o) => sum + o.cents, 0),
}));
console.log('totals  :', totals);

// 缺失桶读出来是 undefined:访问前先判断存在
console.log('missing :', byRegion.latam ?? 'no bucket');