Map object values

OSCC · JavaScript, Object · Oct 21, 2020

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

const mapValues = (obj, fn) =>
  Object.keys(obj).reduce((acc, k) => {
    acc[k] = fn(obj[k], k, obj);
    return acc;
  }, {});
const users = {
  fred: { user: 'fred', age: 40 },
  pebbles: { user: 'pebbles', age: 1 }
};
mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }

Recommended snippets

  • Map object keys

    JavaScript, Object

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

  • Deep merge objects

    JavaScript, Object

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

  • Rename object keys

    JavaScript, Object

    Replaces the names of multiple object keys with the values provided.