0

How can I store an object/array in JavaScript Cookies? I tried that simple code

var item = { 
    price: 200,   
    company: 'Microsoft',   
    quantity: 500,
    code: 'm33'
}

console.log(item);
Cookies.set('item', item);
console.log(Cookies.get('item'));

It shows all the values in the first console message, but gives only "[object Object]" in the second. Looks like js-cookie cannot work with objects correctly. Is there any way I can fix that?

Fagner Brack
  • 2,365
  • 4
  • 33
  • 69

3 Answers3

1

You are storing an object, and cookies are allowed text-only. Remember that cookies have a max-length of 4 KB, so you can't store a lot of information here (use localStorage instead).

To solve this problem, you must to stringify the json first:

Cookies.set('item', JSON.stringify(item));

And you'll store a stringified object. To access it then, you must to parse the string:

console.log(JSON.parse(Cookie.get('item')));
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
0

Just use:

Cookies.getJSON('item')

js-cookie has built-in support for JSON parsing as from version 2.0.0, there is no need to change how you set it. For more information, see https://github.com/js-cookie/js-cookie/tree/v2.1.0#json

Fagner Brack
  • 2,365
  • 4
  • 33
  • 69
-1

In cookie you can only store string. So in order to store object first you convert your object into string. Using this plugin here is an example:

var people = [
    {"id": 123, "name": "Mazahir Eyvazli"},
    {"id": 128, "name": "Mayki Nayki"},
    {"id": 131, "name": "Mike Shinoda"}
];
$.cookie("people", JSON.stringify(people));

If you want to access your people as an object from cookie

// $.cookie("people") will return people object as an string
// therefore we parse it to JSON object
var people = $.parseJSON($.cookie("people"));
// now we can access our object
people[0]["id"] // --> 123
people[1]["name"] // --> Mayki Nayki
Mike
  • 737
  • 1
  • 7
  • 11