Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  36] [ 5]  / answers: 1 / hits: 37252  / 13 Years ago, fri, january 27, 2012, 12:00:00

I have a list of javascript objects:



var people = [
{ 'name' : 'Abel', 'age' : 1 },
{ 'name' : 'Bella', 'age' : 2 },
{ 'name' : 'Chad', 'age' : 3 },
]


I tried to store them in a browser cookie with jQuery $.cookie():



$.cookie(people, people);


I then retrieve this cookie and then try to push another object into it:



var people = $.cookie(people);
people.push(
{ 'name' : 'Daniel', 'age' : 4 }
);


However, this does not work; I analyzed this code in Firebug, and Console noted that people was a string ([object Object],[object Object],[object Object]) and that the push function did not exist.



What is going on? What is the proper way to store and retrieve a list of objects?


More From » jquery

 Answers
18

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));

[#87769] Wednesday, January 25, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;