Object.fromEntries 与 Object.entries:重复键、Symbol 和属性边界的 12 组实测

10-21 5阅读

把虚构库存记录转成对象时,Object.fromEntries 很省语法;再用 Object.entries 拆回来,却未必得到原来的记录。重复键、Symbol、属性描述符和嵌套引用,都可能改变结果。先把数据模型说清楚,再选择转换方式,比看到输出像对象就认为转换成功更可靠。

Object.fromEntries 与 Object.entries:重复键、Symbol 和属性边界的 12 组实测
独立模型生成的概念示意图,展示键值记录与对象的关系,不是真实软件截图,也不代表完整执行顺序。

一、同一个属性键,后面的值覆盖前面

fromEntries 按迭代顺序写入属性,重复键最后一次提供的值生效。覆盖已有字符串属性不会把它移到队尾。数字键 2 会转换成字符串 '2',因此它们会碰撞;'01' 则不会被改写成 '1'。需要保留重复记录时,应保留数组,不能把转换后的对象当作完整历史。

普通对象枚举时,数组索引键先按数值升序排列,其余字符串键按创建顺序排列。不要概括成“所有看起来像数字的键都会排序”。第二组测试同时放入 '10'、2、'01',用于观察这一边界。参见 TC39 属性键顺序。

二、Symbol 能写进去,却不会被 entries 读出来

fromEntries 保留 Symbol 键本身;两个描述相同的 Symbol 依旧可以是不同的键。entries 只收集自有、可枚举、字符串键属性,忽略继承属性、不可枚举属性和 Symbol。因此两者不是无损互逆操作。参见 MDN entries 与 MDN fromEntries。

键转换也可能执行用户代码。对象键会先按字符串提示转成原始值,再得到字符串或 Symbol;不同对象可能落到同一字符串键。若业务需要保留对象身份作为键,可保留 Map,而不是直接转成普通对象。

三、可迭代,不等于元素形状一定正确

外层必须提供有效的同步迭代协议;每个产出项必须是对象,随后读取其 '0' 和 '1' 属性。项不必是数组,也不要求长度恰好为二。缺失的键或值会读到 undefined,而字符串 'ab' 作为一个项会报错。应单独验证业务字段,不能依赖此方法检查记录完整性。参见 TC39 迭代条目算法。

四、新对象不等于深复制或安全过滤

新建的只是外层对象,嵌套值仍可共享引用。entries 读取可枚举访问器时会调用 getter;其异常会向外传播。再经 fromEntries 建立的属性是普通数据属性,不保留 getter、只读约束或原型。本文测试只涉及普通对象,不把结论扩大到任意代理对象的自定义行为。

fromEntries 创建以 Object.prototype 为原型的普通对象;'__proto__' 在这里会成为自有数据属性,不触发原型设置器。但它没有清洗不可信键,更不能保证后续赋值或合并安全。是否允许某个键,仍应由业务规则决定。参见 TC39 fromEntries 与 属性读取规则。

五、复制即跑:十二组断言

把整段代码保存为 test_from_entries.cjs,分别执行 node test_from_entries.cjs 和 node --use-strict test_from_entries.cjs。本次在 Node v24.19.0 实测,两种模式都输出 12/12 groups passed。使用 Node 严格断言;数据均为虚构,无网络请求。

const assert = require('node:assert/strict');
let passed = 0;
function test(name, run) {
  run();
  passed += 1;
  console.log('PASS ' + name);
}

test('01 duplicate keys', () => {
  const obj = Object.fromEntries([['a', 1], ['b', 2], ['a', 3]]);
  assert.deepEqual(Object.entries(obj), [['a', 3], ['b', 2]]);
});

test('02 numeric keys and order', () => {
  const obj = Object.fromEntries([
    ['b', 1], ['10', 10], [2, 'first'], ['01', 1],
    ['a', 2], ['2', 'last']
  ]);
  assert.equal(obj[2], 'last');
  assert.deepEqual(Object.keys(obj), ['2', '10', 'b', '01', 'a']);
  assert.equal(Object.entries(obj)[0][0], '2');
});

test('03 symbols are not entries', () => {
  const one = Symbol('tag');
  const two = Symbol('tag');
  const obj = Object.fromEntries([[one, 1], [two, 2], ['tag', 3]]);
  assert.deepEqual(Object.getOwnPropertySymbols(obj), [one, two]);
  assert.equal(obj[one], 1);
  assert.equal(obj[two], 2);
  assert.deepEqual(Object.entries(obj), [['tag', 3]]);
});

test('04 own enumerable string properties', () => {
  const obj = Object.create({ inherited: 1 });
  Object.defineProperty(obj, 'hidden', { value: 2 });
  obj.visible = 3;
  obj[Symbol('private')] = 4;
  assert.deepEqual(Object.entries(obj), [['visible', 3]]);
});

test('05 property key coercion and collisions', () => {
  const hints = [];
  const key = { [Symbol.toPrimitive](hint) {
    hints.push(hint);
    return 'cedar';
  } };
  const obj = Object.fromEntries([[key, 1], ['cedar', 2]]);
  assert.deepEqual(hints, ['string']);
  assert.deepEqual(obj, { cedar: 2 });
  const collided = Object.fromEntries([[{}, 1], [{}, 2]]);
  assert.deepEqual(Object.entries(collided), [['[object Object]', 2]]);
});

test('06 references stay shared', () => {
  const detail = { count: 1 };
  const source = { detail };
  const pairs = Object.entries(source);
  const copy = Object.fromEntries(pairs);
  assert.notEqual(copy, source);
  assert.equal(copy.detail, detail);
  assert.equal(pairs[0][1], detail);
  copy.detail.count = 2;
  assert.equal(source.detail.count, 2);
});

test('07 iterable and entry shapes', () => {
  function* rows() {
    yield { 0: 'cedar', 1: 7 };
    yield ['solo'];
    yield [];
  }
  assert.deepEqual(Object.fromEntries(rows()), {
    cedar: 7, solo: undefined, undefined: undefined
  });
  assert.deepEqual(Object.fromEntries(new Map([['pine', 8]])), { pine: 8 });
});

test('08 invalid iterators', () => {
  for (const input of [null, undefined, {}, { [Symbol.iterator]: 1 }]) {
    assert.throws(() => Object.fromEntries(input), TypeError);
  }
  const broken = { [Symbol.iterator]() {
    return { next() { return 1; } };
  } };
  assert.throws(() => Object.fromEntries(broken), TypeError);
});

test('09 primitive entries and closing', () => {
  for (const entry of [null, 4, 'ab']) {
    assert.throws(() => Object.fromEntries([entry]), TypeError);
  }
  let closed = false;
  function* rows() {
    try { yield ['ok', 1]; yield 4; }
    finally { closed = true; }
  }
  assert.throws(() => Object.fromEntries(rows()), TypeError);
  assert.equal(closed, true);
});

test('10 ordinary object and proto data', () => {
  const value = { label: 'fictional' };
  const obj = Object.fromEntries([['__proto__', value]]);
  assert.equal(Object.getPrototypeOf(obj), Object.prototype);
  assert.equal(Object.hasOwn(obj, '__proto__'), true);
  assert.deepEqual(Object.getOwnPropertyDescriptor(obj, '__proto__'), {
    value, writable: true, enumerable: true, configurable: true
  });
  assert.equal(Object.hasOwn(obj, 'label'), false);
  assert.equal(obj.label, undefined);
});

test('11 getters run and errors propagate', () => {
  let reads = 0;
  const source = { get count() { reads += 1; return 7; } };
  const copy = Object.fromEntries(Object.entries(source));
  assert.equal(reads, 1);
  assert.equal(copy.count, 7);
  assert.equal(reads, 1);
  assert.equal(Object.getOwnPropertyDescriptor(copy, 'count').get, undefined);
  const failure = new Error('fictional getter');
  assert.throws(() => Object.entries({ get x() { throw failure; } }),
    error => error === failure);
});

test('12 descriptors and prototypes do not roundtrip', () => {
  const source = Object.create(null);
  Object.defineProperty(source, 'fixed', {
    value: 9, enumerable: true, writable: false, configurable: false
  });
  const copy = Object.fromEntries(Object.entries(source));
  assert.equal(Object.getPrototypeOf(source), null);
  assert.equal(Object.getPrototypeOf(copy), Object.prototype);
  assert.deepEqual(Object.getOwnPropertyDescriptor(copy, 'fixed'), {
    value: 9, writable: true, enumerable: true, configurable: true
  });
  copy.fixed = 10;
  assert.equal(source.fixed, 9);
  assert.equal(copy.fixed, 10);
});

assert.equal(passed, 12);
console.log('12/12 groups passed');

落地前的检查

先确认重复键是否允许覆盖,再确认字符串化是否改变键的身份;需要 Symbol、描述符或独立嵌套值时,另选明确的保留或复制方案。最后检查输入项结构和 getter 副作用。测试验证的是这些语义,不承诺转换速度,也不替代数据校验。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。