Mapping Object Values With entries And fromEntries
Object.entries pairs keys with values and Object.fromEntries rebuilds the record, so per-value transforms and key renames run without hand-written loops.
Code
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
{ shirt: 5000, socks: 2700, cap: 1800 }
total: 9500
{ maxRetries: 3, pollMs: 250 }A pass through the statements
The file’s state is a handful of top-level bindings: cart, lineTotals, total, snake.
The top-level object literal pins max_retries, poll_ms as plain values — no derivation, no imports behind them.
What to watch for
- The whole dependency story is the language version itself.
Putting it to use
The run emits 1 labeled section — total: — one per step.
Core lines
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,
]),
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `cart`, `lineTotals`, `total`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.