Is it possible to create a cookie using arrays?
I would like to store a[0]='peter'
, a['1']='esther'
, a['2']='john'
in a cookie in JavaScript.
Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.
Example - store array in a cookie: var arr = ['foo', 'bar', 'baz']; var json_str = JSON. stringify(arr); createCookie('mycookie', json_str);
JavaScript can create, read, and delete cookies with the document. cookie property.
Store objects in the CookiesThe cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.
As you can read in this topic:
You combine the use jQuery.cookie plugin and JSON and solve your problem.
When you want to store an array, you create an array in JS and use JSON.stringify
to transform it into an string and stored with $.cookie('name', 'array_string')
var myAry = [1, 2, 3]; $.cookie('name', JSON.stringify(myAry));
When you want to retrive the array inside the cookie, you use $.cookie('name')
to retrive the cookie value and use JSON.parse
to retrive the array from the string.
var storedAry = JSON.parse($.cookie('name')); //storedAry -> [1, 2, 3]
Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.
You could do this with a JSON library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With