← 中文资源

简体中文版本

Object.entries 与 fromEntries 往返变换

Object.entries 把对象变成键值元组数组,变换后用 Object.fromEntries 重组:四舍五入、键名归一化、按频次排序都保持键不变,中间态是普通数组。

阅读英文原文

运行结果

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

{"usd":110,"eur":101,"jpy":16500}
{"CACHE-CONTROL":"no-store","ACCEPT":"application/json"}
{"to":2,"be":2,"or":1,"not":1}

实现说明

循环只出现在 for (const word of words) tally[word] = (tally[word] ?? 0) + 1;,它的每次迭代处理一个元素。 prices、rounded、flags、upper 定义在模块顶层,中间不经过函数作用域。 模块级对象字面量,键名固定:usd、eur、jpy。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 跨调用保留的状态放在这些顶层绑定里:prices、rounded、flags。

核心语句

for (const word of words) tally[word] = (tally[word] ?? 0) + 1;

代码示例

// 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));