Flattening a Deeply Nested Object: A Step-by-Step Guide
Chiranjit Dey
Posted on August 13, 2024
Understanding the Problem
Often, we encounter complex data structures in JavaScript applications. These structures can be deeply nested objects, making it challenging to manipulate or process them directly. One common operation is to flatten these objects, transforming them into a simpler structure where all properties are at the top level.
In this blog, we'll delve into a JavaScript code snippet that effectively flattens a deeply nested object. We'll break down the code line by line, explaining its logic and functionality.
The Code Breakdown
let user = {
name : 'Chiranjit',
address : {
personal : {
city: 'Kolkata',
state: 'West Bengal'
},
office : {
city: 'Bengaluru',
state: 'Karnataka',
area: {
landmark:'Waterside',
post: 433101
}
}
}
}
var finalObj = {}
const flatObjFn = (obj, parent) => {
for(let key in obj){
if(typeof obj[key] === 'object'){
flatObjFn(obj[key], parent+'_'+key)
}else{
finalObj[parent + '_' + key] = obj[key]
}
}
}
flatObjFn(user, 'user');
console.log(finalObj);
Line-by-Line Explanation
- Creating the Nested Object:
- We begin by creating a deeply nested object named user. It contains properties like name, address, and further nested objects within address.
-
Initializing the Output Object:
- An empty object finalObj is created to store the flattened result.
-
Defining the Flattening Function:
- A function named flatObjFn is defined, accepting two parameters: a) obj: The object to be flattened. b) parent: A string to prefix property names for clarity.
-
Iterating Through Object Properties:
- A for...in loop iterates over each property of the input object obj.
-
Handling Nested Objects:
- If the value of a property is an object, the flatObjFn function is recursively called on that object. The parent parameter is concatenated with the current property name to create a new prefix for the nested properties.
-
Handling Primitive Values:
- If the value of a property is not an object (i.e., a primitive value like a string or number), it's added to the finalObj with a key formed by concatenating the parent and the current property name.
-
Calling the Flattening Function:
- The flatObjFn is called with the user object as input and 'user' as the initial parent prefix.
-
Logging the Flattened Object:
- The final flattened object is printed to the console using console.log(finalObj).
How It Works?
The flatObjFn function recursively traverses the object, breaking down nested structures into a flat object. The parent parameter keeps track of the object hierarchy, allowing the function to create meaningful property names in the output object.
Posted on August 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.