Skip to content

Instantly share code, notes, and snippets.

@PawanKolhe
Created September 18, 2020 06:13
Show Gist options
  • Select an option

  • Save PawanKolhe/b3c824301efcd6d69fedd5f79bbc9409 to your computer and use it in GitHub Desktop.

Select an option

Save PawanKolhe/b3c824301efcd6d69fedd5f79bbc9409 to your computer and use it in GitHub Desktop.
Flattens object, separating keys with underscores
const user = {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496",
"location": {
"name" : "Another galaxy"
}
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
};
const newObj = {};
const flatten = (obj, parentKey) => {
if(!(typeof obj === 'object' && obj !== null)) {
return [obj, parentKey];
}
for(const key in obj) {
const result = flatten(obj[key], parentKey + '_' + key);
if(Array.isArray(result)) {
newObj[result[1]] = result[0];
}
}
}
flatten(user, 'user');
console.log(newObj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment