Flattening a javascript object is a very common question asked in UI Interviews.
Flattening deeply nested object can be easily achieved by using recursive technique.
The code depends on how a flattened object should look like...
// input var user = { name: "Vishal", address: { primary: { house: "109", street: { main: "21", cross: "32" } } } }; //output { user_name: "Vishal", user_address_primary_house: "109", user_address_primary_street_main: "21", user_address_primary_street_cross: "32", }
Algo:
- Iterate over keys of the object
- Append child key name into the parent key name
- If the child key's value is an object again call the same function
- Else assign key to the new value
Code:
var flattendObj = {}; const flattenObject = (obj, keyName) => { Object.keys(obj).forEach(key => { var newKey = `${keyName}_${key}` if (typeof obj[key] === "object") { // calling the function again flattenObject(obj[key], newKey); } else { flattendObj[newKey] = obj[key]; } }); }; console.log(flattendObj);
Recursion is magical, if you know where to stop. 🌀
Follow me for more such content.
Aiming to post the solution of such problems daily. 🔥
Challenge me with more problems. 💪
Top comments (1)
This will not pass in many test cases. Its not a right code.