Skip to content

Instantly share code, notes, and snippets.

@iamshadmirza
Created December 6, 2019 02:38
Show Gist options
  • Save iamshadmirza/0a9b07d449c7381ee2f69e119f4f5519 to your computer and use it in GitHub Desktop.
Save iamshadmirza/0a9b07d449c7381ee2f69e119f4f5519 to your computer and use it in GitHub Desktop.
Iterate through object and flatten it.
//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