---
title: "Map function for objects instead of arrays"
description: "When working with JavaScript or TypeScript, the Array.prototype.map() method is immensely useful for transforming array elements. However, what if you want to…"
url: https://www.danny.engineering/answer/javascript/map-function-for-objects-instead-of-arrays
author: Danny
published: 2025-02-04T00:00:00.000Z
updated: 2025-02-07T23:50:00.000Z
tags: ["Javascript"]
---

# Map function for objects instead of arrays

When working with JavaScript or TypeScript, the `Array.prototype.map()` method is immensely useful for transforming array elements. However, what if you want to perform a similar transformation on an object’s properties or values? By default, JavaScript does not provide a `map()` function for objects. This limitation can lead to confusion and inefficient code when developers try to achieve this functionality manually. Let’s delve into solving this problem with practical strategies.

## Problem

The `Array.prototype.map()` method is designed specifically for arrays, allowing you to iterate over each array element and produce a new array by applying a callback function. However, when working with objects, there’s no native `map` equivalent. 

For example, if you have an object like this:

```javascript
const person = {
  name: "Alex",
  age: 30,
  active: true,
};
```

You might want to create a new object where all values are transformed while keeping their original keys:

```javascript
const transformed = {
  name: "ALEX",
  age: 31,
  active: false,
};
```

Because objects in JavaScript are not iterable like arrays, applying mapping transformations efficiently becomes non-trivial. This issue commonly arises when dealing with APIs, configuration objects, or dynamic data structures. Without proper strategies, developers often write overly verbose or repetitive code.

## Solution

Here are two common approaches to implement a "map" behaviour for objects.

### **Using `Object.entries`, `Object.fromEntries`, and Functional Programming**

This approach leverages `Object.entries()` to transform the object into an array of key-value pairs, applies a transformation with `map()`, and then reconstructs the object using `Object.fromEntries()`.

- `Object.entries(obj)` converts the object into an array of `[key, value]` pairs.
- You apply `Array.map()` to transform the pairs as needed.
- `Object.fromEntries()` converts the modified pairs back into a new object.

```javascript
const mapObject = (obj, callback) => {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value]) => {
      // Apply the callback to transform the value
      return [key, callback(value, key)];
    })
  );
};

// Example usage
const person = {
  name: "Alex",
  age: 30,
  active: true,
};

const transformed = mapObject(person, (value, key) => {
  if (typeof value === "string") return value.toUpperCase(); // Transform strings
  if (typeof value === "number") return value + 1; // Increment numbers
  if (typeof value === "boolean") return !value; // Toggle booleans
  return value;
});

console.log(transformed);
// Output: { name: "ALEX", age: 31, active: false }
```



- This method ensures immutability by creating a new object rather than modifying the original.
- The transformation applies only to `own` properties, not inherited ones.
- Adding extra logic for deeply nested objects will require additional recursion.

#### **Functional Approach with `reduce()`**

The `reduce()` method can be used directly to iterate over the object’s keys, apply transformations, and build a new object in place.

- Use `Object.keys()` or `Object.entries()` to iterate over the properties.
- Use the accumulator pattern provided by `reduce()` to construct the transformed object.

```javascript
const mapObject = (obj, callback) => {
  return Object.keys(obj).reduce((acc, key) => {
    acc[key] = callback(obj[key], key); // Apply transformation
    return acc; // Build the new object
  }, {});
};

// Example usage
const person = {
  name: "Alex",
  age: 30,
  active: true,
};

const transformed = mapObject(person, (value, key) => {
  return typeof value === "number" ? value * 2 : value; // Example transformation
});

console.log(transformed);
// Output: { name: "Alex", age: 60, active: true }
```

- This method is slightly more manual but offers flexibility in constructing the transformed object.
- Like the previous solution, it does not support nested transformation out of the box.

### Further Considerations

1. **Performance and Complexity:**
   - Both approaches handle objects with a small or moderate number of properties efficiently. For large objects, consider testing performance, as `entries` and transformations can add overhead.

2. **Immutability:**
   - Always be cautious when mutating the original object. Both methods above ensure a new object is created, preserving the original data structure.

3. **Nested Objects:**
   - If you need to "map" deeply nested objects, you will need to implement recursion or use libraries such as [Lodash](https://lodash.com/). Lodash provides utility methods like `_.mapValues` that can handle complex use cases.

4. **TypeScript Integration:**
   - If you’re using TypeScript, add proper types for objects and callbacks to ensure type safety in your transformations.

### Related Resources

- [MDN Web Docs: Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
- [MDN Web Docs: Object.fromEntries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)
- [Lodash Documentation](https://lodash.com/docs/)
- [MDN Web Docs: Array.prototype.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
