Created
September 7, 2015 06:55
-
-
Save duncanmcdougall/fe683ea72412a956e735 to your computer and use it in GitHub Desktop.
Flattens a nested javascript object into a flat object with long keys with .'s and [0]'s
This file contains 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 nested javascript object into a flat object with long keys with .'s and [0]'s */ | |
function FlattenJavaScriptObject(toFlatten, prefix) { | |
var result = {}; | |
var traveseObject = function (theObject, path) { | |
if (!(typeof theObject === 'string') && theObject instanceof Array) { | |
for (var i = 0; i < theObject.length; i++) { | |
var key = path + "[" + i + "]"; | |
if (typeof theObject[i] === 'string') { | |
result[key] = theObject[i]; | |
} else { | |
traveseObject(theObject[i], key); | |
} | |
} | |
} | |
else { | |
if (path.length > 0) { | |
path = path + "."; | |
} | |
for (var prop in theObject) { | |
if (theObject[prop] instanceof Object || (theObject[prop] instanceof Array && !(typeof theObject[prop] === 'string' || theObject[prop] instanceof String))) | |
traveseObject(theObject[prop], path + prop); | |
else { | |
var key = path + prop; | |
result[key] = theObject[prop]; | |
} | |
} | |
} | |
} | |
traveseObject(toFlatten, prefix); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment