AlexGalax
AlexGalax

Reputation: 310

jQuery arrays into cookie

var adddata = [];
adddata[ group ] = [];
adddata[ group ][ id ] = option; // option is an object like { foo : 'bar' }

console.log( adddata ); // looks ok

$.cookie( 'cookiename', JSON.stringify( adddata ) );
console.log( $.cookie( 'cookiename' ) ); // just "[]"
$.cookie( 'cookiename', adddata );
console.log( $.cookie( 'cookiename' ) ); // "an empty string"

// in another file
var cdata = JSON.parse( $.cookie( 'cookiename' ) );
$.each( cdata, function( group, items ){
    /* and so on */
});

As you can see, I use the $.cookie plugin. But how can I store arrays into the cookie the right way?

Thanks & regards, Alex

Upvotes: 1

Views: 1585

Answers (2)

Felix Kling
Felix Kling

Reputation: 817208

If group and id are not numeric values, JSON.stringify will ignore them. Only numeric properties are taken into account when converting an array to JSON.

See:

> a = []
  []
> a['foo'] = 5
  5
> a[0] = 42
  42
> JSON.stringify(a)
  "[42]"

You have to use an object {} if you deal with non-numerical properties:

> a = {}
  Object
> a['foo'] = 5
  5
> JSON.stringify(a)
  "{"foo":5}"

Never use a JavaScript array as associative array. JS arrays should only have numerical keys. For everything else, use plain objects.

Upvotes: 4

JAAulde
JAAulde

Reputation: 19560

Serialization is required before storage since a cookie can only be a string. However, there are JS/jQ cookie libraries available which attempt to transparently handle the un/serialization for you. The most popular cookie library which people use with jQuery (the one you are using) does not attempt to handle this for you, so your extra step is required.

Edit: Ah, I missed part of the question regarding the serialization not resulting in the correct value. See Felix Kling's answer, it is correct.

Upvotes: 1

Related Questions