Skip to content

Instantly share code, notes, and snippets.

@jansanchez
Created September 25, 2013 03:23
Show Gist options
  • Save jansanchez/6694824 to your computer and use it in GitHub Desktop.
Save jansanchez/6694824 to your computer and use it in GitHub Desktop.
How do I store an array of objects in a cookie with jQuery $.cookie()?
/*
Cookies can only store strings. Therefore, you need to convert your array of objects into a JSON string.
If you have the JSON library, you can simply use JSON.stringify(people) and store that in the cookie,
then use $.parseJSON(people) to un-stringify it.
In the end, your code would look like:
*/
var people = [
{ 'name' : 'Abel', 'age' : 1 },
{ 'name' : 'Bella', 'age' : 2 },
{ 'name' : 'Chad', 'age' : 3 },
];
$.cookie("people", JSON.stringify(people));
// later on...
var people = $.parseJSON($.cookie("people");)
people.push(
{ 'name' : 'Daniel', 'age' : 4 }
);
$.cookie("people", JSON.stringify(people));
@williamli
Copy link

JSON.parse can also be used to replace $.parseJSON

@SSYT
Copy link

SSYT commented Feb 11, 2018

Thanks :)

@dannypage
Copy link

Perfect example, thank you!

@devkongnc
Copy link

How about remove each items?

@Benazere
Copy link

thanks dude that was helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment