Skip to content

Instantly share code, notes, and snippets.

@duncanmcdougall
Created September 7, 2015 06:55
Show Gist options
  • Save duncanmcdougall/fe683ea72412a956e735 to your computer and use it in GitHub Desktop.
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
/* 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