Last active
June 30, 2020 16:00
-
-
Save toandv/bc6ce04a4d19f27aceb1ad968713033d to your computer and use it in GitHub Desktop.
flatten json objecct
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
Object.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