Files
30-seconds-of-code/snippets/to-hash.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

681 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Iterable to hash array sleepy-cat 2018-05-31T02:14:04+03:00 2022-01-30T12:45:30+03:00

Reduces a given iterable into a value hash (keyed data store).

  • Use Object.values() to get the values of the iterable (object or array).
  • Use Array.prototype.reduce() to iterate over the values and create an object, keyed by the reference value.
const toHash = (object, key) =>
  Object.values(object).reduce((acc, data, index) => {
    acc[!key ? index : data[key]] = data;
    return acc;
  }, {});
toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }
toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }