Check if formdata object key exists

ajax, forms, html, javascript, jquery-ui

Solution

Things are changing and nowadays you can check if key exits using get function.

Original answer

As we already discussed in comments, browser hides data which is stored in `FormData` object due to security reasons. There is one workaround which helps to preview its data in developer console which is described here: FormData.append("key", "value") is not working

The only way to have access to such data in code is to use own wrapping object, which supports appending data, getting values and converting to `FormData`. It could be an object like this:

function FormDataUnsafe() {
    this.dict = {};
};

FormDataUnsafe.prototype.append = function(key, value) {
    this.dict[key] = value;
};

FormDataUnsafe.prototype.contains = function(key) {
    return this.dict.hasOwnProperty(key);
};

FormDataUnsafe.prototype.getValue = function(key) {
    return this.dict[key];
};

FormDataUnsafe.prototype.valueOf = function() {
    var fd = new FormData();
    for(var key in this.dict) {
        if (this.dict.hasOwnProperty(key))
            fd.append(key, this.dict[key]);
    }

    return fd;
};

FormDataUnsafe.prototype.safe = function() {
    return this.valueOf();
};

Usage:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data.safe());  // convertion here

Demo

Problem

Is it possible to run a check on a key for the formdata object? I would like to know if a key has already been assigned a value. tried something like this with negative results ``` data=new FormData(); if(!data.key) data.append(key,somevalue); ``` addition question is the nature of a double assignment to rewrite the original value?

Original source

Related problems