mapObj

Same as Array.prototype.map, but for objects.

1. Code

/**
 * Maps over the properties of an object and applies a callback function to each property.
 *
 * @template T - The type of the values in the input object.
 * @template U - The type of the values in the output object.
 * @param {Record<string, T>} obj - The input object.
 * @param {(value: T, key: string, obj: Record<string, T>) => U} callback - The callback function to apply to each property.
 * @returns {Record<string, U>} - The resulting object with the mapped properties.
 */

const mapObj = <T, U>(
  obj: Record<string, T>,
  callback: (value: T, key: string, obj: Record<string, T>) => U
): Record<string, U> => {
  const result: Record<string, U> = {};

  // loop through each key in the object
  for (const key in obj) {
    // check if the key is a property of the object
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      result[key] = callback(obj[key], key, obj);
    }
  }

  return result;
};

export default mapObj;

2. Installation

npx @jrtilak/lazykit@latest add mapObj -ts

3. Description

The mapObj function is a utility function that applies a callback function to each property of an input object and returns a new object with the results. This function is similar to the Array.prototype.map method for arrays, but it works with objects.

The function is generic and can work with objects of any type. It takes two type parameters: T and U. T is the type of the values in the input object, and U is the type of the values in the output object.

The function accepts two parameters: obj and callback. obj is the input object, and callback is a function that gets applied to each property of obj. The callback function takes three parameters: value, key, and obj. value is the current property's value, key is the current property's key, and obj is the original input object.

4. Props

Prop

Type

Default Value

object*object---
callback*function---

5. Examples

import mapObj from ".";

const obj1 = { a: 1, b: 2, c: 3 };
const result1 = mapObj(obj1, (value: number) => value * 2);
console.log(result1);
// Expected output:  { a: 2, b: 4, c: 6 }

const obj2 = {};
const result2 = mapObj(obj2, (value: any) => value);
console.log(result2);
// Expected output:  {}

const obj3 = { 1: "one", 2: "two", 3: "three" };
const result = mapObj(obj3, (value: string, i) => value.toUpperCase() + i);
console.log(result);
// Expected output: { 1: 'ONE1', 2: 'TWO2', 3: 'THREE3' }