Object.fromEntries Rebuilds Keyed Records

Rebuild objects from key-value pairs with Object.fromEntries: filter and remap header pairs, convert Maps to plain objects, and let later duplicate keys win.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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 }

What the code does

Module-level bindings hold the data — headers, pairs, normalized, counts — with no function scope in between.

Applying it

The demo output is labeled (pairs:, custom headers:, from map:), so every printed line maps back to its originating operation.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `headers`, `pairs`, `normalized`.