Last active
March 6, 2017 05:52
-
-
Save lhr0909/4307adcdd9eb8bc2edffcec4bf1c22e1 to your computer and use it in GitHub Desktop.
flattens javascript object to work with expressjs body-parser with `extended: true`
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
| 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