How To Achieve Array.map() Functionality With Objects

js array map functionality with objects

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. In this tutorial you will learn how to achieve map function functionality with objects in JavaScript with code examples.

Using Object.entries() with Array.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]) => {
        return [key, value * 2];
    })
);

console.log(transformedObj);
// Output: { a: 2, b: 4, c: 6 }
  • Object.fromEntries() is a static method available in JavaScript’s Object class. It creates a new object from an iterable (such as an array) containing key-value pairs.
  • Object.entries() is a method in JavaScript’s Object class introduced in ECMAScript 2017 (ES8). It returns an array containing key-value pairs of the enumerable properties of an object. Each key-value pair is represented as a two-element array, where the first element is the property key and the second element is the property value.

Using a Custom Function:

You can define a custom function that iterates over the object’s properties and applies a transformation. Here is an example:

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 }

This code defines a function called mapObject that takes an object obj and a function fn as arguments. It then iterates through each key of the input object, applies the provided function to the corresponding value, and creates a new object with the transformed values. Finally, it returns the resulting object.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy