Efthyvoulos Tsouderos Efthyvoulos Tsouderos - 5 months ago 11
Javascript Question

jQuery/JavaScript code explanation

I was looking for a way to convert form data to JavaScript object with jQuery and I came across this thread: Convert form data to JavaScript object with jQuery
The most popular answer has this code in it:

$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) { // ???
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};


However there is a piece of code in it that I am not exactly sure of what is doing(I think is a mistake)

if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}


Objects do not have a property named push. There is a JS array method
.push()
which, besides pushing elements into the array, it returns the number of elements in the array, but in this case there are no braces let alone that, as you can see,
o
is an object. I tried this code with console.log but it never executes. Do any of you have any idea, what is the purpose of this if statement? This code is in other threads as well so I am not sure who the author of this code is.

Thank you in advance

Answer

It's a stupid way to check if o[this.name] is an array:

if (!$.isArray(o[this.name])) {
    o[this.name] = [o[this.name]];
}

The reason for this however is if you have multiply form elements with the same name:

<input type="checkbox" name="a[]" value="1">
<input type="checkbox" name="a[]" value="2">

If both are checked the output will be converted to an array instead of a string:

{
  "a": ["1", "2"]
}

And if only one is checked:

{
  "a": "1"
}
Comments