Back to Functions

mapValues

object

Creates an object with the same keys as object and values generated by running each own enumerable string keyed property of object thru iteratee.

Installation

Import
import { mapValues } from '@tulx/utils';

Source Code

Implementation
/**
 * Creates an object with the same keys as object and values generated by running each own enumerable string keyed property of object thru iteratee.
 *
 * @param object - The object to iterate over.
 * @param iteratee - The function invoked per iteration.
 * @returns Returns the new mapped object.
 *
 * @example
 * ```ts
 * const users = {
 *   'fred': { 'user': 'fred', 'age': 40 },
 *   'pebbles': { 'user': 'pebbles', 'age': 1 }
 * };
 * mapValues(users, (o) => o.age); // { 'fred': 40, 'pebbles': 1 }
 * ```
 */
export function mapValues<T, TResult>(
  object: Record<string, T>,
  iteratee: (value: T, key: string) => TResult
): Record<string, TResult> {
  const result: Record<string, TResult> = {};
  for (const key in object) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      result[key] = iteratee(object[key], key);
    }
  }
  return result;
}

Example

import { mapValues } from '@tulx/utils';

const users = {
'fred': { 'user': 'fred', 'age': 40 },
'pebbles': { 'user': 'pebbles', 'age': 1 }
};
mapValues(users, (o) => o.age); // { 'fred': 40, 'pebbles': 1 }

Related Functions