Object.entries 与 fromEntries:往返转换会丢掉什么?

把对象拆成键值对、筛选后再装回去,是整理配置和接口字段的常用写法。但 Object.fromEntries(Object.entries(obj)) 并非无损往返:哪些键能进入列表、重名键留下谁、结果如何排序,都有明确边界。先确定你需要的是字段转换,还是保留对象完整结构,才能避免把一次便捷转换误当成复制协议。
本文的对象行为限定在普通对象,内建函数未被改写;另用基本类型说明入口转换,不把结论推广到代理对象或任意不可信输入。以下五个文件均在 Node.js v24.19.0 实测,直接用 node 加文件名运行,无需安装依赖;示例只操作内存并打印结果,不读写文件或访问网络。断言不通过时会立即报错。
一、entries 只取自身、可枚举、字符串键
先看三道筛选条件。继承来的属性不属于“自身”,不可枚举属性不会被收集,Symbol 键即使可枚举也被跳过。下面刻意把四种属性放在同一个对象上,结果只留下 visible。不要用输出列表的长度反推源对象到底有多少属性,也不要把这份列表当作完整的对象清单。
这项筛选发生在 entries 端。对于依赖符号键传递内部标记的代码,后续再调用 fromEntries 也无法找回已经被省略的键。
文件:01-scope.mjs;运行:node 01-scope.mjs
import assert from 'node:assert/strict';
const token = Symbol('token');
const source = Object.create({ inherited: 9 });
source.visible = 1;
source[token] = 3;
Object.defineProperty(source, 'hidden', { value: 2 });
const entries = Object.entries(source);
assert.deepEqual(entries[0], ['visible', 1]); // A01
assert.equal(entries.some(([k]) => k === 'inherited'), false); // A02
assert.equal(entries.some(([k]) => k === 'hidden'), false); // A03
assert.equal(entries.some(([k]) => typeof k === 'symbol'), false); // A04
console.log(JSON.stringify(entries));
实际标准输出:
[["visible",1]]
二、两端接受的输入并不对称
fromEntries 消费同步可迭代输入,生成器可以逐项交出键值对,而且传入的 Symbol 可以成为结果的键。普通对象不会自动被解释为键值对列表。迭代出来的每一项还必须是对象;字符串 ab 虽然可迭代,却不能充当合格的条目对象。规范读取条目的 0 和 1 属性,因此条目并不强制必须是真正的数组。
entries 则先做对象转换,不负责消费迭代器。字符串 ab 的索引字符会成为条目;数字转换后的包装对象没有自身可枚举属性,所以得到空数组;null 和 undefined 无法这样转换,会抛出 TypeError。遇到空结果时,应先检查数据类型,而不是直接认定原数据为空。
文件:02-inputs.mjs;运行:node 02-inputs.mjs
import assert from 'node:assert/strict';
const token = Symbol('token');
function* pairs() {
yield ['name', 'demo'];
yield [token, 7];
}
const result = Object.fromEntries(pairs());
assert.equal(result.name, 'demo'); // A05
assert.equal(result[token], 7); // A06
assert.throws(() => Object.fromEntries({ name: 'demo' }), TypeError); // A07
assert.throws(() => Object.fromEntries(['ab']), TypeError); // A08
assert.deepEqual(Object.entries('ab'), [['0', 'a'], ['1', 'b']]); // A09
assert.deepEqual(Object.entries(42), []); // A10
assert.throws(() => Object.entries(null), TypeError); // A11
assert.throws(() => Object.entries(undefined), TypeError); // A12
console.log(JSON.stringify(Object.entries(result)));
console.log(`symbol=${result[token]}`);
console.log(JSON.stringify(Object.entries('ab')));
实际标准输出:
[["name","demo"]] symbol=7 [["0","a"],["1","b"]]
三、最后的值与最终的顺序分别判断
同一个属性键出现多次,后面的值覆盖前面的值;但覆盖已有属性不会把它重新排到末尾。数字键 1 会转换为字符串键,与字符串 1 落到同一属性上,所以这里留下 string-wins。使用表单或配置条目时,若业务不允许重复,应在转换前检查,不能等结果生成后再恢复被覆盖的数据。
普通对象枚举时,数组索引键先按数值升序出现,其余字符串键再按创建先后排列。因而先输入 10、再输入 2,输出仍是 2 在前;01 和 -1 虽然看起来像数字,却不是数组索引键。需要保留完整输入顺序以及重复项时,应继续保存原条目序列。
文件:03-order-duplicates.mjs;运行:node 03-order-duplicates.mjs
import assert from 'node:assert/strict'; const result = Object.fromEntries([ ['10', 'ten'], ['2', 'two'], ['01', 'padded'], ['label', 'first'], ['-1', 'negative'], ['label', 'last'], [1, 'number'], ['1', 'string-wins'] ]); assert.deepEqual(Object.keys(result), ['1', '2', '10', '01', 'label', '-1']); // A13 assert.equal(result.label, 'last'); // A14 assert.equal(result[1], 'string-wins'); // A15 assert.equal(Object.entries(result).every(([k]) => typeof k === 'string'), true); // A16 console.log(JSON.stringify(Object.entries(result)));
实际标准输出:
[["1","string-wins"],["2","two"],["10","ten"],["01","padded"],["label","last"],["-1","negative"]]
四、往返只重建容器,不深拷贝值
返回的新对象与源对象身份不同,嵌套 child 却仍是同一个引用。改动 copy.child.count,源对象的嵌套值也会改变。此外,entries 会读取属性值,因此示例中的 getter 被执行一次;fromEntries 保存的是当次返回的数值,不是 getter 函数。后续修改 child,不会让 copy.total 自动重算。
属性描述符也没有随键值对保留:原先不可写的 locked,在新对象上变成可写的数据属性。如果目标是复制访问器、只读约束或原型,需要另选明确保留这些结构的方案,并单独决定嵌套数据是否共享。
文件:04-roundtrip.mjs;运行:node 04-roundtrip.mjs
import assert from 'node:assert/strict';
let reads = 0;
const source = {
child: { count: 1 },
get total() { reads++; return this.child.count; }
};
Object.defineProperty(source, 'locked', { value: 9, enumerable: true });
const copy = Object.fromEntries(Object.entries(source));
assert.notEqual(copy, source); // A17
assert.equal(copy.child, source.child); // A18
assert.equal(reads, 1); // A19
assert.equal(Object.getOwnPropertyDescriptor(copy, 'total').get, undefined); // A20
assert.equal(Object.getOwnPropertyDescriptor(copy, 'locked').writable, true); // A21
copy.child.count = 2;
assert.equal(source.child.count, 2); // A22
assert.equal(copy.total, 1); // A23
console.log(`reads=${reads}; shared=${copy.child === source.child}`);
console.log(`source.count=${source.child.count}; copy.total=${copy.total}`);
实际标准输出:
reads=1; shared=true source.count=2; copy.total=1
五、__proto__ 是数据键,不是安全通行证
fromEntries 在新对象上创建自身数据属性。这里的 __proto__ 存下 payload,不会调用传统的原型设置器;结果的原型仍然是 Object.prototype,marker 也不会因此变成继承属性。用属性描述符核验,比仅打印 result.__proto__ 更容易分清“同名字段”与真正的对象原型。
这个局部性质不能推出后续任意合并都安全。在提供传统 __proto__ 设置器的环境里,把该键再通过普通赋值写入另一个对象,可能触发设置器;深层合并还有自己的路径处理规则。迭代器、getter 和键转换本身也可能执行代码。处理外部数据时仍应限制字段、校验形状,并审查后续使用方式。
文件:05-proto-data.mjs;运行:node 05-proto-data.mjs
import assert from 'node:assert/strict';
const payload = { marker: 'data' };
const result = Object.fromEntries([['__proto__', payload]]);
const descriptor = Object.getOwnPropertyDescriptor(result, '__proto__');
assert.equal(Object.getPrototypeOf(result), Object.prototype); // A24
assert.equal(descriptor.value, payload); // A25
assert.equal(descriptor.enumerable, true); // A26
assert.equal(descriptor.writable, true); // A27
assert.equal(descriptor.configurable, true); // A28
assert.equal(result.marker, undefined); // A29
console.log(`prototype unchanged=${Object.getPrototypeOf(result) === Object.prototype}`);
console.log(JSON.stringify(result));
console.log(`own data=${descriptor.value === payload}; inherited marker=${result.marker}`);
实际标准输出:
prototype unchanged=true
{"__proto__":{"marker":"data"}}
own data=true; inherited marker=undefined
把边界写进测试,再用于业务转换
实测记录:五个示例包含二十九条编号断言,全部通过。另制作五个各改错一条断言的独立测试变体,分别误认符号键会被收集、普通对象可直接输入、重复键先到先得、嵌套值被克隆、原型会被替换,五次均实际触发断言失败。复跑次数和反向变体中复制的断言不重复计数。
实践时先问三件事:允许丢掉哪些字段,如何处理重复与顺序,哪些引用必须隔离。答案明确后,再把这两个函数放进转换链。规范来源于北京时间二〇二六年十月二十三日核对的 TC39 当前在线草案;本文不把这些既有语义描述为当天新发布的功能。

