1

I'm serializing a form as follows (inspired by this answer):

function formToArray(jQueryObj){
var result = {};
var arr = jQueryObj.serializeArray();
$.each(arr, function(){
    result[this.name] = this.value;
});
return result;
}

This returns an object such as {"input1_name":"value1", "input2_name": "42"}. However, some of the inputs are numeric, and I want them to return numbers instead of strings. So my desired output is {"input1_name":"value1", "input2_name": 42}, the number not in quotes.

How can I achieve this with jQuery/JavaScript?

Thanks,

Community
  • 1
  • 1
jeff
  • 13,055
  • 29
  • 78
  • 136

5 Answers5

3

If you want to convert the string back into a number you can use Number():

$.each(arr, function(){
  if (!isNaN(this.value)) { //check if value is convertible to number
    result[this.name] = Number(this.value);
  } else {
    result[this.name] = this.value;
  }
});
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
1

You can manually check if the value is number.

$.each(arr, function(){
  if (!isNaN(this.value)) { //Check for non numbers negation
    result[this.name] = Number(this.value);
  } else {
    result[this.name] = this.value;
  }
});
squiroid
  • 13,809
  • 6
  • 47
  • 67
1

Parse the value and check it with isNaN

function formToArray(jQueryObj){
var result = {};
var arr = jQueryObj.serializeArray();
$.each(arr, function(){
   result[this.name] =isNaN(parseInt(this.value))?this.value:parseInt(this.value);
});
return result;
}
Sajan
  • 813
  • 9
  • 14
1

You can try this:

var result = { };
$.each($('form').serializeArray(), function() {
    result[this.name] = Number(this.value) ? Number(this.value) : this.value;
});
Doanh
  • 56
  • 3
1

you can use "string" * 1 to coerce to a number

it's faster than using Number and parseInt
also, if you use parseInt remember to pass the radix 10 parseInt(number, 10)

var converted = this.value*1;
result[this.name] = isNaN(converted) ? this.value : converted;
aw2basc
  • 23
  • 1
  • 6