实现说明
顶层就这几处状态:cart、lineTotals、total、snake。
模块级对象字面量,键名固定:max_retries、poll_ms。
使用要点
- 演示输出是带标签的(
total:),每个操作都会留下自己的一行标注。
常见问题
它依赖第三方库吗?
没有引用任何第三方库,标准库就够了。 跨调用保留的状态放在这些顶层绑定里:cart、lineTotals、total。
核心语句
const total = Object.values(lineTotals).reduce((sum, cents) => sum + cents, 0);
Object.entries(snake).map(([key, value]) => [
key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()),
value,
]),
代码示例
const cart = {
shirt: { cents: 2500, qty: 2 },
socks: { cents: 900, qty: 3 },
cap: { cents: 1800, qty: 1 },
};
// Object.entries pairs each key with its value; Object.fromEntries
// rebuilds the record, so per-value transforms keep their keys
const lineTotals = Object.fromEntries(
Object.entries(cart).map(([item, { cents, qty }]) => [item, cents * qty]),
);
console.log(lineTotals);
const total = Object.values(lineTotals).reduce((sum, cents) => sum + cents, 0);
console.log("total:", total);
// Same recipe on keys: snake_case identifiers into camelCase
const snake = { max_retries: 3, poll_ms: 250 };
const camel = Object.fromEntries(
Object.entries(snake).map(([key, value]) => [
key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()),
value,
]),
);
console.log(camel);