Object.entries And fromEntries Value Mapping
Transform every value of an object with Object.entries and rebuild it via Object.fromEntries, keeping keys intact through rounding, renaming, and sorting.
Code
// Object.entries + Object.fromEntries: 键不变的值变换往返
const prices = { usd: 100, eur: 92, jpy: 15000 };
// entries 把对象变成 [key, value] 元组数组,变换后再组装回对象
const rounded = Object.fromEntries(
Object.entries(prices).map(([code, amount]) => [code, Math.round(amount * 1.1)]),
);
console.log(JSON.stringify(rounded));
// 键名归一化:统一转大写
const flags = { 'Cache-Control': 'no-store', Accept: 'application/json' };
const upper = Object.fromEntries(
Object.entries(flags).map(([key, value]) => [key.toUpperCase(), value]),
);
console.log(JSON.stringify(upper));
// 词频统计后按出现次数排序重建
const words = 'to be or not to be'.split(' ');
const tally: Record<string, number> = {};
for (const word of words) tally[word] = (tally[word] ?? 0) + 1;
const ranked = Object.fromEntries(
Object.entries(tally).sort((a, b) => b[1] - a[1]),
);
console.log(JSON.stringify(ranked));Output
Captured from a sandboxed run of this snippet in the build pipeline.
{"usd":110,"eur":101,"jpy":16500}
{"CACHE-CONTROL":"no-store","ACCEPT":"application/json"}
{"to":2,"be":2,"or":1,"not":1}How it works
Iteration happens inside for (const word of words) tally[word] = (tally[word] ?? 0) + 1; — everything outside it runs once.
Top-level bindings prices, rounded, flags, upper hold the demo state — nothing sits inside a function scope.
The top-level object literal pins usd, eur, jpy as plain values — no derivation, no imports behind them.
Statements that matter
for (const word of words) tally[word] = (tally[word] ?? 0) + 1;
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `prices`, `rounded`, `flags`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.