Map object keys

OSCC · JavaScript, Object · Oct 21, 2020

Maps the keys of an object using the provided function, generating a new object.

const mapKeys = (obj, fn) =>
  Object.keys(obj).reduce((acc, k) => {
    acc[fn(obj[k], k, obj)] = obj[k];
    return acc;
  }, {});
mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }

Recommended snippets

  • Map object values

    JavaScript, Object

    Maps the values of an object using the provided function, generating a new object with the same keys.

  • Deep merge objects

    JavaScript, Object

    Deeply merges two objects, using a function to handle keys present in both.

  • Deep map object keys

    JavaScript, Object

    Deep maps an object's keys.