Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if formdata object key exists

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?

like image 781
Alex_Nabu Avatar asked Oct 21 '22 14:10

Alex_Nabu


1 Answers

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

like image 73
Tony Avatar answered Oct 23 '22 04:10

Tony