Last active
August 29, 2015 14:01
-
-
Save blowsie/1f6e8584b48e8a4f6dbf to your computer and use it in GitHub Desktop.
JSON Flatten / Unflatten - Demo: http://fiddle.jshell.net/blowsie/S2hsS/show/light/
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; | |
}; | |
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[""] || resultholder; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment