Redwall
Redwall

Reputation: 1020

Store Array to Cookie Jquery

I am creating an array in my code which looks like this

Array [ "type", "year", "week" ]

When I save this to a cookie and read it again it formats as

Array [ "type,year,week" ]

How can I keep the original format Array [ "type", "year", "week" ] I guess it is getting stripped down to a CSV when it is added to the cookie.

Thanks in advance

My code:

var myArray = [ "type", "year", "week" ]
$.cookie('setup', myArray, { path: '/' }); // set up cookie 

Upvotes: 0

Views: 1247

Answers (1)

techfoobar
techfoobar

Reputation: 66663

Cookies store string values.

You need to serialize your array (with JSON or join with a predefined delimiter) before storing it into a cookie and deserialize it when reading it back.

For example:

// store into cookie
$.cookie('setup', myArray.join('|'), { path: '/' });
OR
$.cookie('setup', JSON.stringify(myArray), { path: '/' });

// read from cookie
myArray = $.cookie('setup').split('|');
OR
myArray = JSON.parse($.cookie('setup'));

Note: The JSON versions are safer since they'll work with any kind of array. The former assumes that your array elements do not contain | in them.

Upvotes: 5

Related Questions