2

I need to serialize an associative JavaScript array. It's a simple form of products and a numeric values, but just after building the array seems empty.

The code is here: http://jsbin.com/usupi6/4/edit

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Fabio Mora
  • 5,339
  • 2
  • 20
  • 30

3 Answers3

7

In general, don't use JS arrays for "associative arrays". Use plain objects:

var array_products = {};

That is why $.each does not work: jQuery recognizes that you pass an array and is only iterating over numerical properties. All others will be ignored.

An array is supposed to have only entries with numerical keys. You can assign string keys, but a lot of functions will not take them into account.


Better:

As you use jQuery, you can use jQuery.param [docs] for serialization. You just have to construct the proper input array:

var array_products = []; // now we need an array again
$( '.check_product:checked' ).each(function( i, obj ) {
    // index and value
    var num = $(obj).next().val();
    var label = $(obj).next().next().attr( 'data-label' );
    // build array
    if( ( num > 0 ) && ( typeof num !== undefined ) ) {
        array_products.push({name: label, value: num});
    }      
});

var serialized_products = $.param(array_products);

No need to implement your own URI encoding function.

DEMO


Best:

If you give the input fields a proper name:

<input name="sky_blue" class="percent_product" type="text" value="20" />

you can even make use of .serialize() [docs] and greatly reduce the amount of code (I use the next adjacent selector [docs]):

var serialized_products = $('.check_product:checked + input').serialize();

(it will include 0 values though).

DEMO

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
5

You could serialise it with a JSON library (or the native JSON object if available).

var serialised = JSON.stringify(obj);
alex
  • 479,566
  • 201
  • 878
  • 984
2

JSON.stringify(object)

As a sidenote there are no associative arrays there are only objects.

Use json-js to support legacy browsers like IE6 and IE7

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • Isn't JSON.stringify only available to more modern browsers? Unless you include a script reference to [json2.js](https://github.com/douglascrockford/JSON-js)? – Ash Clarke Jun 22 '11 at 10:51
  • @AshClarke depends on your definition of modern browsers. It's supported by all current & recent browsers. If you need _legacy_ support use json2 (I've added the link already) – Raynos Jun 22 '11 at 10:53
  • 1
    @Raynos won't `let arr = []; a['foo'] = 'bar'; JSON.stringify(a);` stringify it to '[]' – ShrekOverflow Nov 23 '15 at 16:44