Hayden E
Hayden E

Reputation: 108

How do I use document.cookie to store and retrieve the values in an array?

I am storing and retrieving values in cookies using methods:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
};

and

function getCookie() {
    var name = "name=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}; 

Now I need to store/retrieve arrays in a similar fashion. I know I'll need to create the array as a single string and then parse it back but what is the best way to do this?

Upvotes: 2

Views: 2609

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138267

Assuming, you want to store/retrieve multiple cookies.Your get Cookie thing nearly does it:

function getCookies() {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
return ca.map(function(c){
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
        return c.split("=");
    }
});
}; 

You just have to return all, not the first, and you need to remove the namedetection.

console.log(getCookies());

SetCookies:

function setCookies(Cookies,exp){
 Cookies.forEach(function(el){setCookie(el[0],el[1],exp);});
}

setCookies([
  ["name","value"]
 ]);

Upvotes: 0

Samuel Reid
Samuel Reid

Reputation: 1756

I recommend using JSON. First, you convert the array into a JSON string:

var array = ["one","two","three"];
var json_string = JSON.stringify(array);

Then you set the cookie with the JSON string as the value.

setCookie("array", json_string, exdays);

Then when you retrieve the JSON string from the cookie later, convert it back into an actual array.

var json_string = getCookie("array");
var array = JSON.parse(json_string);

Upvotes: 5

Related Questions