Back to Functions

mapKeys

object

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

Installation

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

Source Code

Implementation
/**
 * Creates an object with the same values as object and keys 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
 * mapKeys({ 'a': 1, 'b': 2 }, (value, key) => key + value); // { 'a1': 1, 'b2': 2 }
 * ```
 */
export function mapKeys<T>(
  object: Record<string, T>,
  iteratee: (value: T, key: string) => string
): Record<string, T> {
  const result: Record<string, T> = {};
  for (const key in object) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      const newKey = iteratee(object[key], key);
      result[newKey] = object[key];
    }
  }
  return result;
}

Example

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

mapKeys({ 'a': 1, 'b': 2 }, (value, key) => key + value); // { 'a1': 1, 'b2': 2 }

Related Functions