How to use the Lodash library In Typescript

In this approach, we will use lodash library provided by NPM to flatten the given object. It provides several functions such as flatten, flattenDeep, and flatMap which allow us to recursively flatten nested objects and arrays.

Syntax:

const result: any = lodash.flatten(object);

Steps to use lodash with TypeScript:

  • Step 1: Create a directory with the project name in your local system. Open the terminal and run the following commands to start with the project.
npm install lodash
npm install ts-node --save-dev
  • Step 2: After installation, create a file app.ts in the root directory of the project and define a function flattenObject that utilizes lodash’s forEach() and flatten() method to flatten the object.
  • Step 3: It constructs new keys by concatenating parent keys with child keys, separating them with dots.
  • Step 4: Finally, it returns the resulting flattened object.
  • Step 5: Run the application using the below command.
npx ts-node app.ts

Project Structure:

Example: The below code implements the lodash library to flatten the nested object in TypeScript.

Javascript
const lodash = require('lodash');

let obj = {
    company: "w3wiki",
    members: {
        John: "USA",
    },
    technology: {
        language: "HTML, CSS",
        library: {
            name: "Node JS",
        },
    },
};

function flattenObject(obj: Record<string, any>):
    Record<string, any> {
    const resultObj: Record<string, any> = {};

    function flatten(obj: Record<string, any>, prefix = '') {
        lodash.forEach(obj, (value: any, key: string) => {
            const newKey = prefix ? `${prefix}.${key}` : key;
            if (lodash.isObject(value)) {
                flatten(value, newKey);
            } else {
                resultObj[newKey] = value;
            }
        });
    }

    // Recursively calling flatten function
    flatten(obj);
    return resultObj;
}

const flattenedObject = flattenObject(obj);
console.log(flattenedObject);
console.log("Accessing flattened properties: ")
console.log(flattenedObject['technology.language']);
console.log(flattenedObject['technology.library.name']);

Output:

company: "w3wiki"
members.John: "USA"
technology.language: "HTML, CSS"
technology.library.name: "Node JS"
Accessing flattened properties:
HTML, CSS
Node JS

How to Flatten Dynamically Nested Objects in Order in TypeScript ?

We are required to flatten a Typescript nested object that contains arrays and objects as children such that there should be no nested children left and everything should be at the same height.

Example:

Input: obj = {
    subject: "Computer Networks",
    students: {
        Jake: "USA"
    }
};
Output: obj = {
    "subject": "Computer Networks",
    "students.Jake": "USA"
}

Table of Content

  • Using Recursion
  • Using the Lodash library

Similar Reads

Using Recursion

Recursion is a programming technique that is used to solve different problems. In this technique, a function calls itself again and again until the terminating condition met. We can use this to flatten a nested object in TypeScript....

Using the Lodash library

In this approach, we will use lodash library provided by NPM to flatten the given object. It provides several functions such as flatten, flattenDeep, and flatMap which allow us to recursively flatten nested objects and arrays....

Custom function without external libraries

In this approach, we’ll create a custom function to recursively flatten the nested object. This approach allows us to understand the logic behind flattening nested objects without relying on external libraries....