Skip to content

Instantly share code, notes, and snippets.

@ryan-scott-dev
Last active August 29, 2015 13:57
Show Gist options
  • Save ryan-scott-dev/9383147 to your computer and use it in GitHub Desktop.
Save ryan-scott-dev/9383147 to your computer and use it in GitHub Desktop.
Flatten Nested JSON data to Form Data
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