Computer >> Computer tutorials >  >> Programming >> Javascript

How can I store JavaScript objects in cookies?


To store JavaScript objects in cookies, use JSON stringify. It is used to convert a JavaScript value to a JSON string.

The following code snippet to learn how to store JavaScript objects in cookies −

(function(){
   var myObject = JSON.parse('{"id":1,"gender":"male"}');
   var e = 'Thu Nov 26 2017 15:44:38'; document.cookie = 'myObj='+ JSON.stringify(myObject) +';expires=' + e;
})()