0

I have jquery array like this:

[1: "0", 2: "0,1,2,3"]

I want to save this in browser cookie. But As far I know only string can be saved in browser cookie. So I have to convert this jquery array into string and then save in cookie. Is there any way to do this?

  • 3
    [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)? I imagine there's a good duplicate for "how to serialize data structure to string in JavaScript" somewhere around here... – apsillers Apr 18 '16 at 14:32
  • Possible duplicate of [Cookie Array in javascript](http://stackoverflow.com/questions/8163815/cookie-array-in-javascript) – Nikos Paraskevopoulos Apr 18 '16 at 15:42
  • Possible duplicate of [I want to store Javascript array as a Cookie](http://stackoverflow.com/questions/2980143/i-want-to-store-javascript-array-as-a-cookie) – snovelli Apr 18 '16 at 16:10

2 Answers2

0

Cookies can only store strings. Therefore, you need to convert your array into a JSON string. If you have the JSON library, you can simply use JSON.stringify(data) and store that in the cookie, then use $.parseJSON(data) to un-stringify it.

In the end, your code would look like:

var data = [
   { 'name' : 'Abel', 'age' : 1 },
   { 'name' : 'Bella', 'age' : 2 },
   { 'name' : 'Chad', 'age' : 3 },
];

$.cookie("data", JSON.stringify(data));
// later on if you need to add any element...
var data = $.parseJSON($.cookie("data"));
data.push(
    { 'name' : 'Daniel', 'age' : 4 }
);
$.cookie("data", JSON.stringify(data));
Jainil
  • 1,488
  • 1
  • 21
  • 26
0

[1: "0", 2: "0,1,2,3"] this is not a array and it is wrong writing; {1: "0", 2: "0,1,2,3"} if you write like this, it is a object, so you can do like this:

var target = {1: "0", 2: "0,1,2,3"};
for(let name in target){
  document.cookie = name + "=" +  target[name];
}
SF_bs
  • 1
  • 1