Skip to content

Instantly share code, notes, and snippets.

@erodozer
Forked from penguinboy/Object Flatten
Created March 9, 2016 18:00
Show Gist options
  • Save erodozer/fe4ee36ec14c30861a4b to your computer and use it in GitHub Desktop.
Save erodozer/fe4ee36ec14c30861a4b to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object
/**
* Flattens a json object into a single-dimensional representation
* @param: stripPrefix: boolean
* by default, subobjects will have their property name prefixed to the flattened property name.
* This is done to prevent overwriting of properties with the same name. If this is a non-issue
* for your data type, then feel free to set this to true
* @return: a single dimensional copy of the original object
*/
Object.defineProperty(Object.prototype, 'flatten', {
value: function(stripPrefix) {
var toReturn = {};
for (var i in this) {
if (!this.hasOwnProperty(i)) continue;
if ((typeof this[i]) == 'object' && this[i] != null) {
var obj = this[i];
var flatObject = obj.flatten();
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
var prefix = (stripPrefix == true) ? x : `${i}.${x}`;
toReturn[prefix] = flatObject[x];
}
} else {
toReturn[i] = this[i];
}
}
return toReturn;
},
writable: false,
configurable: false,
enumerable: false
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment