0

I have a set of POST endpoints where I need to send a collection of static parameters plus a few dynamic parameters specific to the request.

For every request, I am doing the following:

var staticParams = {...}, // some arbitrarily large object
    localParams = {...},
    formData = new FormData();

Object.keys(staticParams).forEach(function(key) {
  formData.append(key, staticParams[key]);
});

Object.keys(localData).forEach(function(key) {
  formData.append(key, localParams[key]);
});

It's not a huge tax, but it seems silly to repeat the first enumeration for every request. How can I clone and extend my FormData object so that I don't have to build the whole thing every time?


FWIW, I know how to clone Objects; I believe FormData is unique in that the key/value pairs are not simply keys on the Object, so I am unclear on the correct way to clone it.

Community
  • 1
  • 1
Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • 1
    As far as I know, [such](http://stackoverflow.com/q/22409667/1048572) is not possible. But I don't think repeatedly appending your data for multiple requests doesn't have much of an impact. – Bergi Feb 09 '16 at 15:27
  • @Bergi you've got a double-negative there; do you think this IS a problem or IS NOT a problem? – Evan Davis Feb 09 '16 at 15:40
  • Ooops, I meant that it's NOT a problem - neither space- nor timewise. – Bergi Feb 09 '16 at 15:42
  • var f = function() {this. formData = {'x':'y'};} var newFormData = new f(). formData;, the new keyword should do the trick fast – shay te Feb 22 '16 at 23:11
  • @shayte it doesn't seem like you understand what `FormData` is? https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData – Evan Davis Feb 23 '16 at 13:55

1 Answers1

-2

You could use the following function to be able to extend your objects.

if(Object.prototype.extend === undefined) {
    Object.prototype.extend = function(obj) {
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                this[i] = obj[i];
            }
        }
    };
}

Which adds the properties of the object 'obj' to the object the function is called on.

In your case, you could use it as follows:

formData.extend(staticParams);
formData.extend(localParams);
Koen Morren
  • 1,233
  • 2
  • 9
  • 12
  • 2
    I know how to clone objects (and I certainly would _not_ do it by mucking with the Object prototype,) but `FormData` does not store its values directly as keys on the object. – Evan Davis Feb 09 '16 at 15:01