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

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.