If you’re given a nested object, how do you flatten that object with recursion in JavaScript?
For example, we have this object.
let obj = {
"Key1": 1,
"Key2":{
"1": 2,
"2": 3,
"3":{
"1": 4,
"2" : 5
}
}
};
And we want to flatten it into the following form
let flattenedObj = {
"Key1": 1,
"Key2.1": 2,
"Key2.2": 3,
"Key2.3.1": 4,
"Key2.3.2": 5,
}
How would you do it?
Solution
function flattenObject(obj) {
let flattenedObj = {};
function stringifyObj(object, propName) {
if (typeof object !== 'object') {
flattenedObj[propName] = object;
return;
}
for (let prop in object) {
if (propName === "") stringifyObj(object[prop], prop)
else stringifyObj(object[prop], propName + "." + prop);
}
}
stringifyObj(obj, "");
return flattenedObj;
}
To solve this solution, you need a nested function. The first function is to define a variable to store the result which will be filled with the nested function.
The first function is pretty simple so we’ll focus on the nested function.
As all recursions do, we have a base case. We’ll stop the recursion if the current item is not an object, in that case we’ll just add that property and value to the object with this code.
if (typeof object !== 'object') {
flattenedObj[propName] = object;
return;
}
Then for the next part, we loop through each property in the object, it might be a key-value pair or another nested object.
If it is a key-value pair, we’ll call the function recursively and the base case will stop the recursion and add the value to the object with this code if (propName === "") stringifyObj(object[prop], prop)
. We can tell if it is a nested object or not with the if clause.
If it is an object, this code else stringifyObj(object[prop], propName + "." + prop);
will call the function recursively and flatten the object. You can see that we pass the appended string into the function which concatenate the propName with ‘.’ and the nested propName .
In the end, we return the flattened object when we’re done with the recursion.
Time Complexity : O(n)
Space Complexity : O(n)
We access each property and store them once according to the number of properties.
Summary
That’s how we can flatten an object with recursion in JavaScript.
You essentially call the function until each property is flattened.
If you are interested on another topic about algorithms in JavaScript, check out Check Prime Number in JS.
For you who want to brush up your JavaScript skills, whether to deepen or learn form zero, I recommend you try Codecademy. There are tons of JavaScript lessons that you can learn in a structured and interactive way. You can learn from the most basic materials to advanced stuffs and even preparing for technical interviews. Go try it now!
If you have a better solution be it code-wise or efficiency-wise, please do comment below!
Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript!
See you next post!