Files
30-seconds-of-code/snippets/symbolizeKeys.md
2022-05-14 15:55:07 +03:00

621 B

title, tags, expertise, author, cover, firstSeen
title tags expertise author cover firstSeen
Symbolize object keys object advanced chalarangelo blog_images/rocky-lake.jpg 2021-08-01T05:00:00-04:00

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' }