How to Flatten Dynamically Nested Objects in Order in TypeScript ?
Last Updated :
03 May, 2024
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"
}
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.
Approach:
- Create a function as flattenObject that takes an object as a parameter and returns it as a flattened object. Inside the function, we loop through each property of the input object to check its type.
- If it is an object, we recursively call the flattenObject function on that object. Otherwise, we simply store the value in the resultant object.
- After the given loop ends, we return the object as a result.
- Finally, we call the created function by passing the given response object inside.
Example: The below example illustrates the above approach to flatten the nested objects in TypeScript.
JavaScript
let obj = {
company: "GeeksforGeeks",
members: {
John: "USA",
},
technology: {
language: "HTML, CSS",
library: {
name: "Node JS",
},
},
};
const flattenObject = (obj: any): any => {
let resultObj: any = {};
for (const i in obj) {
if (typeof obj[i] === 'object' &&
!Array.isArray(obj[i])) {
// Recursively invoking the funtion
// until the object gets flatten
const tempObj = flattenObject(obj[i]);
for (const j in tempObj) {
resultObj[i + '.' + j] = tempObj[j];
}
} else {
resultObj[i] = obj[i];
}
}
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: "GeeksforGeeks"
members.John: "USA"
technology.language: "HTML, CSS"
technology.library.name: "Node JS"
Accessing flattened properties:
HTML, CSS
Node JS
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.
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: "GeeksforGeeks",
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: "GeeksforGeeks"
members.John: "USA"
technology.language: "HTML, CSS"
technology.library.name: "Node JS"
Accessing flattened properties:
HTML, CSS
Node JS
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.
Example: In this example we flattens a nested object into a single-level object, preserving structure. It recursively iterates through the object, concatenating keys with dot notation, and assigns values accordingly.
JavaScript
interface NestedObject {
[key: string]: any;
}
const obj: NestedObject = {
company: "GeeksforGeeks",
members: {
Nikunj: "Surat",
},
technology: {
language: "HTML, CSS",
library: {
name: "Node JS",
},
},
};
function flattenObject(obj: NestedObject, parentKey = ''): NestedObject {
const flattened: NestedObject = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
const nestedKey = parentKey ? `${parentKey}.${key}` : key;
if (typeof value === 'object' && value !== null) {
const nestedFlattened = flattenObject(value, nestedKey);
Object.assign(flattened, nestedFlattened);
} else {
flattened[nestedKey] = value;
}
}
}
return flattened;
}
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": "GeeksforGeeks",
"members.Nikunj": "Surat",
"technology.language": "HTML, CSS",
"technology.library.name": "Node JS"
}
"Accessing flattened properties:"
"HTML, CSS"
"Node JS"
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read