Skip to content

Instantly share code, notes, and snippets.

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