Created
November 5, 2015 19:54
-
-
Save chrisl8888/8e9dea35011ab07796d3 to your computer and use it in GitHub Desktop.
JSON Flatten - http://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects
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
| JSON.flatten = function(data) { | |
| var result = {}; | |
| function recurse (cur, prop) { | |
| if (Object(cur) !== cur) { | |
| result[prop] = cur; | |
| } else if (Array.isArray(cur)) { | |
| for(var i=0, l=cur.length; i<l; i++) | |
| recurse(cur[i], prop + "[" + i + "]"); | |
| if (l == 0) | |
| result[prop] = []; | |
| } else { | |
| var isEmpty = true; | |
| for (var p in cur) { | |
| isEmpty = false; | |
| recurse(cur[p], prop ? prop+"."+p : p); | |
| } | |
| if (isEmpty && prop) | |
| result[prop] = {}; | |
| } | |
| } | |
| recurse(data, ""); | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment