ramirez ramirez - 29 days ago 9x
JSON Question

How to set variable in JSON cookie?

I'm using js.cookie.js Github and trying to set a JSON cookie.
In documentation of js.cookie.js mentioned that if you want set a JSON cookie you must do like this:

Cookies.set('name', { foo: 'bar' });

so the cookie data will be like below if you call

{ foo: 'bar' }

Now my question is how to set
from a javascript variable. I tried this but was not useful:

var myVar = 'foo';
Cookies.set('name', { myVar: 'bar' });

the result was
{ myVar: 'bar' }
and not
{ foo: 'bar' }

My JSFIDDLE.COM test: https://jsfiddle.net/nz2ur613/

document.onload = Do();
   function Do() {
   var myvar = 'foo';
   var obj = {} ;
   obj[myvar] = 'bar';
   Cookies.set('name', obj);

I created an object and then set it to cookie.

Try this one. It will work

Demo : https://jsfiddle.net/snuny9om/