How To Use map() Function For Objects (instead Of Arrays)

In JavaScript, the map() function is typically used with arrays to transform each element of the array and return a new array with the results. However, when working with objects, you can achieve similar functionality using other methods or by iterating over the object’s properties. Here’s how you can achieve this:

1. Using Object.entries() and Array.prototype.map()

You can use the Object.entries() method to get an array of key-value pairs (arrays) of the object’s properties, and then use map() on that array to transform each key-value pair.

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const transformedObj = Object.fromEntries(
    Object.entries(obj).map(([key, value]) => [key, value * 2])
);

console.log(transformedObj);
// Output: { a: 2, b: 4, c: 6 }

2. Using a Custom Function

You can define a custom function that iterates over the object’s properties and applies a transformation.

function mapObject(obj, fn) {
    const result = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            result[key] = fn(obj[key]);
        }
    }
    return result;
}

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const transformedObj = mapObject(obj, (value) => value * 2);

console.log(transformedObj);
// Output: { a: 2, b: 4, c: 6 }

In conclusion, there’s no direct map() method for objects like there is for arrays, you can achieve similar functionality by using methods like Object.entries() combined with map() or by creating custom functions. These approaches allow you to iterate over an object’s properties and apply transformations as needed.