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.
interface NestedObject {
[key: string]: any;
}
const obj: NestedObject = {
company: "w3wiki",
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": "w3wiki",
"members.Nikunj": "Surat",
"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