实现说明
演示用的数据放在这几个模块级绑定中: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);