Skip to content

Instantly share code, notes, and snippets.

@everdimension
Created October 26, 2015 18:01
Show Gist options
  • Save everdimension/55a441622440d6bd1b37 to your computer and use it in GitHub Desktop.
Save everdimension/55a441622440d6bd1b37 to your computer and use it in GitHub Desktop.
Append nested object to FormData. The object can be just one level deep. For anything more complex it is recommended to rethink the way you send such data to the server.
(function() {
'use strict';
if (window.FormData) {
FormData.prototype.appendObject = function (obj, namespace) {
// EXAMPLE:
// var person = { name: 'some name', age: 87 };
// var fd = new FormData();
// fd.appenObject(obj, 'person');
// This appends the keys of the object like this:
// fd.append('person[name]', 'some name');
// fd.append('person[age]', 87);
var keyName;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keyName = [namespace, '[', key, ']'].join('');
this.append(keyName, obj[key]);
}
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment