DEV Community

Avnish
Avnish

Posted on

1

Recursively Mapping Objects in JavaScript

Recursively Mapping Objects in JavaScript

Recursively mapping objects in JavaScript involves traversing through nested objects and applying a function to each key-value pair. This process allows for transforming the structure of an object according to a specific logic or requirement.


1. Using a Recursive Function

This approach involves defining a recursive function that iterates through each key-value pair of the object, checking if the value is another object. If it is, the function recursively calls itself to map the nested object.

Example:

function mapObject(obj, fn) {
    return Object.fromEntries(
        Object.entries(obj).map(([key, value]) => {
            if (typeof value === 'object' && value !== null) {
                return [key, mapObject(value, fn)];
            }
            return [key, fn(value)];
        })
    );
}

const obj = {
    a: 5,
    b: {
        c: 6,
        d: {
            e: 7
        }
    }
};

const mappedObject = mapObject(obj, value => value * 2);
console.log(mappedObject);
Enter fullscreen mode Exit fullscreen mode

Output:

{ "a": 10, "b": { "c": 12, "d": { "e": 14 } } }
Enter fullscreen mode Exit fullscreen mode

2. Using Object.keys() and Array.reduce()

This approach utilizes Object.keys() to get an array of keys from the object and Array.reduce() to iterate through each key-value pair. If the value is an object, the function recursively applies the mapping logic.

Example:

function mapObject(obj, fn) {
    return Object.keys(obj).reduce((acc, key) => {
        const value = obj[key];
        acc[key] = (typeof value === 'object' && value !== null)
            ? mapObject(value, fn)
            : fn(value);
        return acc;
    }, {});
}

const obj = {
    a: 2,
    b: {
        c: 4,
        d: {
            e: 6
        }
    }
};

const mappedObject = mapObject(obj, value => value * 2);
console.log(mappedObject);
Enter fullscreen mode Exit fullscreen mode

Output:

{ "a": 4, "b": { "c": 8, "d": { "e": 12 } } }
Enter fullscreen mode Exit fullscreen mode

3. Utilizing Libraries such as Lodash or Ramda

Libraries like Lodash and Ramda provide utility functions to work with objects and collections. These libraries offer functions such as _.mapValues() in Lodash or R.map() in Ramda, which can be used to recursively map objects with ease.

Example (Using Lodash):

const _ = require('lodash');

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

const fn = value => value * 2;
const mapObject = (obj, fn) =>
    _.mapValues(obj, value => (typeof value === 'object' && value !== null)
        ? mapObject(value, fn)
        : fn(value));

const mappedObject = mapObject(obj, fn);
console.log(mappedObject);
Enter fullscreen mode Exit fullscreen mode

Output:

{ "a": 2, "b": { "c": 4, "d": { "e": 6 } } }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Recursively mapping objects in JavaScript can be done using pure JavaScript functions like recursion with Object.entries() or Array.reduce(), or by utilizing external libraries such as Lodash for more concise implementations. Each approach has its use case, depending on the complexity of the data structure and the need for performance optimization.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more