30秒学会 JavaScript 片段 · 2023年1月8日

30秒学会 JavaScript 片段 – Symbolize object keys

Creates a new object, converting each key to a Symbol.

  • Use Object.keys() to get the keys of obj.
  • Use Array.prototype.reduce() and Symbol to create a new object where each key is converted to a Symbol.

代码实现

const symbolizeKeys = obj =>
  Object.keys(obj).reduce(
    (acc, key) => ({ ...acc, [Symbol(key)]: obj[key] }),
    {}
  );

symbolizeKeys({ id: 10, name: 'apple' });
// { [Symbol(id)]: 10, [Symbol(name)]: 'apple' }

翻译自:https://www.30secondsofcode.org/js/s/symbolize-object-keys