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
How to Iterate Array of Objects in TypeScript ?
In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Table of Content Using for..
4 min read
How to Define Interfaces for Nested Objects in TypeScript ?
In TypeScript, defining interfaces for nested objects involves specifying the structure of each level within the object hierarchy. This helps ensure that the nested objects adhere to a specific shape or pattern. Here are step-by-step instructions on how to define interfaces for nested objects in Typ
2 min read
How to Cast Object to Interface in TypeScript ?
In TypeScript, sometimes you need to cast an object into an interface to perform some tasks. There are many ways available in TypeScript that can be used to cast an object into an interface as listed below: Table of Content Using the angle bracket syntaxUsing the as keywordUsing the spread operatorU
3 min read
How do I dynamically assign properties to an object in TypeScript?
In TypeScript, we can not assign the properties dynamically to an object directly by using the dot operator and the square brackets syntax which we generally use to assign dynamic properties in Vanilla JavaScript. JavaScript is a dynamically typed language and the type of a variable is determined at
3 min read
How to Convert an Array of Objects into Object in TypeScript ?
Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript. We are given an array of objects
3 min read
How to move Duplicate to First Index in an Array of Objects in TypeScript ?
To efficiently rearrange an array of objects in TypeScript, moving duplicates to the first index, The approach is first to identify the duplicate within the array, then to remove the duplicate from its current position in the array then at last to re-insert the duplicate at the first index of the ar
7 min read
How to Create Objects with Dynamic Keys in TypeScript ?
In TypeScript, objects with dynamic keys are those where the key names are not fixed and can be dynamically determined at runtime. This allows the creation of flexible data structures where properties can be added or accessed using variables, providing more versatile type definitions. These are the
3 min read
How to Cast a JSON Object Inside of TypeScript Class ?
Casting a JSON object to a TypeScript class involves converting a plain JSON object (which lacks methods and proper typing) into an instance of a class that includes all the defined methods and type safety of that class. Types of Objects in TypeScriptPlain Objects: When parsing JSON data using the J
3 min read
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.
6 min read
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
5 min read