Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to store Javascript array as a Cookie

Is it possible, I have a some sort of list and I want to store it on browser, if it is not possible, what is the efficient way of doing this?

like image 543
Oguz Bilgic Avatar asked Jun 05 '10 11:06

Oguz Bilgic


People also ask

Can array be stored in cookie?

Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode ).

How are arrays stored in JavaScript?

In Javascript, an array is a Hashtable Object type so the interpreter doesn't need to keep track of physical memory and changing the value of an element doesn't affect other elements as they're not stored in a contiguous block of memory.

Can we store array inside array in JavaScript?

An array is an ordered collection of values: each value is called an element, and each element has a numeric position in the array, known as its index. JavaScript lets us create arrays inside array called Nested Arrays.

How does JSON store data in cookies?

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. Also, we will retrieve the object from the cookies.


1 Answers

JSON encode it, effectively producing a string like "{name:'myname',age:'myage'}" which you put in a cookie, retrieve when needed and decode back into a JavaScript array/object.

Example - store array in a cookie:

var arr = ['foo', 'bar', 'baz']; var json_str = JSON.stringify(arr); createCookie('mycookie', json_str); 

Later on, to retrieve the cookie's contents as an array:

var json_str = getCookie('mycookie'); var arr = JSON.parse(json_str); 

Note: cookie functions are not native, taken from How do I create and read a value from cookie?

like image 179
George Kagan Avatar answered Sep 19 '22 21:09

George Kagan