Last active
August 29, 2015 13:57
-
-
Save ryan-scott-dev/9383147 to your computer and use it in GitHub Desktop.
Flatten Nested JSON data to Form Data
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
flattenNestedFormJSON = function(json) { | |
if (typeof json === "string" || | |
typeof json === "number" || | |
typeof json === "boolean" || | |
json === null) { | |
return json; | |
} | |
if (typeof json !== "object") { | |
return null; | |
} | |
var formDataJson = {}; | |
for (var property in json) { | |
if (!json.hasOwnProperty(property)) { | |
continue; | |
} | |
var value = json[property]; | |
if (value === null || value === undefined) { | |
continue; | |
} | |
if ($.isArray(value)) { | |
for (var i = 0; i < value.length; i++) { | |
var elementProperty = property + '[' + i + ']'; | |
formDataJson[elementProperty] = flattenNestedFormJSON(value[i]); | |
} | |
} else { | |
formDataJson[property] = value; | |
} | |
} | |
return formDataJson; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment