Jquery form serializeArray to string

6.1k views Asked by At

How to convert this array to string separated by commas with jquery?

var array = $('#form').serializeArray();

Thanks!

2

There are 2 answers

2
Kimtho6 On

You can do it like this:

    var array = $('#form').serializeArray();
    var arrayString = '';

    jQuery.each(array, function () {
        if (arrayString == '' || arrayString == null) {
            arrayString = this + "";
        }
        else {
            arrayString = arrayString + "," + this;
        }
    });

Or

var array = $('#form').serializeArray();
arr = jQuery.map(array , function(n, i){
  return (n.toUpperCase() + i);
});
var arrayString = array.join(",");
2
Luca Filosofi On
$(function () {
  var ATTRIBUTE_SEPARATOR = ":";
  var PROPERTY_SEPARATOR = ", ";

  // EXAMPLE 1
  var serialize_array = $("#form").serializeArray();

  console.log(serialize_array);

  var converted_string_1 = $.map(serialize_array, function (prop, i) {
    return prop.name + ATTRIBUTE_SEPARATOR + prop.value;
  }).join(PROPERTY_SEPARATOR);

  console.log(converted_string_1);
  // a:a, b:b, c:c, d[]:d1, d[]:d2

  // EXAMPLE 2
  var serialized_string = $("#form").serialize();
  var converted_string_2 = decodeURIComponent(
    serialized_string
      .replace(/\&/g, PROPERTY_SEPARATOR)
      .replace(/\=/g, ATTRIBUTE_SEPARATOR)
  );

  console.log(converted_string_2);
  // a:a, b:b, c:c, d[]:d1, d[]:d2

  // EXAMPLE 3
  var converted_string_3 = JSON.stringify(serialize_array);

  console.log(converted_string_3);
  // [{"name":"a","value":"a"},{"name":"b","value":"b"},{"name":"c","value":"c"},{"name":"d[]","value":"d1"},{"name":"d[]","value":"d2"}]
});