Skip to content

Instantly share code, notes, and snippets.

@tehshane
Created May 25, 2019 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tehshane/7242f078a7b6fd66e3071a8c739ebbc2 to your computer and use it in GitHub Desktop.
Save tehshane/7242f078a7b6fd66e3071a8c739ebbc2 to your computer and use it in GitHub Desktop.
Flatten an object to a single depth
/*
* @fileoverview Flatten an object to a single layer deep
* @author Muthukrishnan (https://stackoverflow.com/users/1173436/muthukrishnan)
* @url https://stackoverflow.com/a/53739792
*/
function flattenObject (ob) {
const toReturn = {};
for (const i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object' && ob[i] !== null) {
const flatObject = flattenObject(ob[i]);
for (const x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment