30秒学会 JavaScript 片段 · 2023年3月17日

30秒学会 JavaScript 片段 – Transform object

Applies a function against an accumulator and each key in the object (from left to right).

  • Use Object.keys() to iterate over each key in the object.
  • Use Array.prototype.reduce() to apply the specified function against the given accumulator.

代码实现

const transform = (obj, fn, acc) =>
  Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);

transform(
  { a: 1, b: 2, c: 1 },
  (r, v, k) => {
    (r[v] || (r[v] = [])).push(k);
    return r;
  },
  {}
); // { '1': ['a', 'c'], '2': ['b'] }

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