← 中文资源

简体中文版本

Object.fromEntries 重建键值记录

Object.entries 拆对象、fromEntries 装回去:中间可以对键值对做过滤与改写,Map 借它导出普通对象,重复键后者胜出,适合默认值覆盖场景。

阅读英文原文

运行结果

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

pairs: [ [ 'content-type', 'application/json' ], [ 'x-trace-id', 't-789' ] ]
custom headers: { 'trace-id': 'T-789' }
from map: { errors: 3, warnings: 7 }
merged: { retries: 5, timeout: 30 }

实现说明

演示用的数据放在这几个模块级绑定中:headers、pairs、normalized、counts。

使用要点

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

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件的状态由几个模块级绑定持有:headers、pairs、normalized。

核心语句

const counts = new Map([['errors', 3], ['warnings', 7]]);
.filter(([k]) => k.startsWith('x-'))
.map(([k, v]) => [k.slice(2), v.toUpperCase()]),
);

代码示例

// Object.entries 把对象拆成 [键, 值] 对;fromEntries 把对装回对象
const headers = { 'content-type': 'application/json', 'x-trace-id': 't-789' };
const pairs = Object.entries(headers);
console.log('pairs:', pairs);

// 中间做数组运算:过滤、改键、改值后再重建
const normalized = Object.fromEntries(
  pairs
    .filter(([k]) => k.startsWith('x-'))
    .map(([k, v]) => [k.slice(2), v.toUpperCase()]),
);
console.log('custom headers:', normalized);

// Map 与对象互通:fromEntries 是 Map 的导出口
const counts = new Map([['errors', 3], ['warnings', 7]]);
console.log('from map:', Object.fromEntries(counts));

// 重复键后者胜出:适合做默认值覆盖
const merged = Object.fromEntries([['retries', 3], ['retries', 5], ['timeout', 30]]);
console.log('merged:', merged);