-
-
Save erodozer/fe4ee36ec14c30861a4b to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object
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
/** | |
* 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