Skip to content

Instantly share code, notes, and snippets.

@lhr0909
Last active March 6, 2017 05:52
Show Gist options
  • Select an option

  • Save lhr0909/4307adcdd9eb8bc2edffcec4bf1c22e1 to your computer and use it in GitHub Desktop.

Select an option

Save lhr0909/4307adcdd9eb8bc2edffcec4bf1c22e1 to your computer and use it in GitHub Desktop.
flattens javascript object to work with expressjs body-parser with `extended: true`
function flattenObject(obj, prefix) {
var toReturn = {};
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if ((typeof obj[i]) == 'object') {
var flatObject;
if (prefix) {
prefix = prefix + '[' + i + ']';
} else {
prefix = i;
}
flatObject = flattenObject(obj[i], prefix);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
if (x.indexOf('[') > -1) {
toReturn[x] = flatObject[x];
} else {
toReturn[prefix + '[' + x + ']'] = flatObject[x];
}
}
} else {
toReturn[i] = obj[i];
}
}
return toReturn;
}
/*
flattenObject({a: "b", c: { d: "e", f: "g", h:{i: "j", l: "m", o: {p: "q", r: "s"}}}});
-> {"a":"b","c[d]":"e","c[f]":"g","c[h][i]":"j","c[h][l]":"m","c[h][o][p]":"q","c[h][o][r]":"s"}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment