Created
December 6, 2019 02:38
-
-
Save iamshadmirza/0a9b07d449c7381ee2f69e119f4f5519 to your computer and use it in GitHub Desktop.
Iterate through object and flatten it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Iterate through user object and flatter in one object. | |
//append _ on every level | |
var user = { | |
name: "Shad", | |
address: { | |
personal: { | |
city: "Varanasi", | |
area: "Chauhatta", | |
}, | |
office: { | |
city: "Bangalore", | |
area: { | |
landmark: "Mantri Alpyne", | |
} | |
} | |
} | |
} | |
var result = {}; | |
function magic(user, parent){ | |
for (let key in user){ | |
if(typeof user[key] === 'object'){ | |
magic(user[key], parent + "_" + key); | |
} else { | |
result[parent + "_" + key] = user[key]; | |
} | |
} | |
} | |
magic(user, 'user') | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment