Here’s my much shorter implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | JSON.unflatten = function(data) { "use strict"; if (Object(data) !== data || Array.isArray(data)) return data; var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g, resultholder = {}; for (var p in data) { var cur = resultholder, prop = "", m; while (m = regex.exec(p)) { cur = cur[prop] || (cur[prop] = (m[2] ? [] : {})); prop = m[2] || m[1]; } cur[prop] = data[p]; } return resultholder[""]; }; |
JSON.flatten
hasn’t much changed (and I’m not sure whether you really need those isEmpty
cases):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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) result[prop] = {}; } } recurse(data, ""); return result; } |
Together, they run your benchmark in about the half of the time (Opera 12.16: ~900ms instead of ~ 1900ms, Chrome 29: ~800ms instead of ~1600ms).
from:http://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects