Map object keys

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 }

More like this

  • JavaScript Object Key Transformations

    Easily transform object keys to your liking with this snippet collection.

    Collection · 6 snippets

  • Map object values

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

    JavaScript, Object · Oct 21, 2020

  • Map an object to an array

    Maps an object to an object array, using the provided mapping function.

    JavaScript, Object · Feb 5, 2023

  • Deep merge objects

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

    JavaScript, Object · Jul 25, 2021