How to use a Cookie as an Array in Javascript?

Asked

Viewed 1,664 times

2

Doubt: I would like to know a way to use a Cookie, as if it were a Array.

Problem: I can’t imagine how to do that.

Example: Suppose I have one Array called Foo which would be as follows:

var Foo = ["qualquer coisa, que esteja|escrito-simbolos*e_outros","qualquer coisa, que esteja|escrito-simbolos*e_outros"];

And I’d like to store this information in a Cookie called FooArray, and then I could redeem the value of Cookie and use as a Array.

How could it be done?

3 answers

3


A reliable way would be to transform the array to a String in JSON format:

var Foo = [1,2];
var FooStr  = JSON.stringify(Foo);
var OtherFoo = JSON.parse(FooStr)

The only drawback of this approach compared to join/split is that a few more characters will be required for the JSON format representation. So for number arrays for example, the @Carlos response could save a few bytes.


And to work with cookies I suggest using the plugin jQuery.cookie. To Store:

var Foo = [1,2];
$.cookie('FooCookie', JSON.stringify(Foo));

And to recover:

var OtherFoo = JSON.parse($.cookie('FooCookie'));
  • 1

    Exactly what I thought when I opened the question, the biggest advantage over the other answer is that you might have commas inside the strings.

  • 1

    This is really a great solution, since I’m a fan of JSON, I don’t know how I didn’t think of it before! :)

2

A good practice is to use JSON.

You can convert your object to string with:

JSON.stringify(Foo); 

Before saving the cookie and then recovering with:

Foo = JSON.parse(strCookie);

1

Use the methods Join and split:

var Foo = [1,2];
var cookieData = Foo.join(',');
Foo = cookieData.split(',');
  • But then if you have a comma value it won’t work?

  • I should have given a better example, I’ll edit my question - see it updated, already edited.

  • you can record any string in the cookie. When you recover the value, vc uses the split to convert again to array.

  • Poisé, but see my new example, if the user enters a comma in the value it will be converted into two information

  • Yes, then use another character that your user cannot type, example: |, β, $. You can split using any character.

  • It may be, but I believe that the solution with JSON would be more suitable, simple, and elegant. However, +1 for working.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.