Form.serializeArray () converts each element to string

Trying to create form.serializeArray () and pass the serialized data to the server.

Problem: This method also converts boolean and integer to string. And on the server side based on the value, I am trying to get the datatype because of which it gives me a string every time.

Actual output:  [Object { name="para1", value="1"}, Object { name="para2", value="2"}, Object { name="para3", value="true"}, Object { name="para4", value="rep1"}]

Desired output:

[Object { name="para1", value=1}, Object { name="para2", value=2}, Object { name="para3", value=true}, Object { name="para4", value="rep1"}]

      

Please suggest a solution for this.

+3


source to share


2 answers


You can process the string of value

each object and create a new array with the converted values. For example, strings true

and false

will be converted to their corresponding boolean value, and numbers will be converted to integers. Please note that my example below is quite simple and does not cover all possibilities (floats are also converted to integers).

Edit: As @ sanfor noted in the comments, every line containing an integer is converted to an integer value, although type strings "123"

can also be treated as strings. However, given the information in the question that the input type is unknown, this method gives the desired results.



JSFiddle (open your console to see the result):

var values = [
    {
        name: 'para1',
        value: '1'
    },
    {
        name: 'para2',
        value: 'true'
    },
    {
        name: 'para3',
        value: 'this is a string'
    }
];

var result = values.map(function(obj) {
    var value;

    if (obj.value === 'true') {
        value = true;
    } else if (obj.value === 'false') {
        value = false;
    } else if (!isNaN(obj.value)) {
        value = parseInt(obj.value);
    } else {
        value = obj.value;
    }

    return {
        name: obj.name,
        value: value
    };
});

console.log(result);

      

+5


source


As @Vohuman mentioned, the values ​​are strings as intended. To make them something else, you either need to use some other function to achieve it, or then process the output of the serializeArray.



Most likely the solution is to teach your back-end server to resolve the type based on the field. You usually know what you are expecting in the background, so you also know the type you want and based on what you can (try) make it correct.

+1


source







All Articles