Reputation: 13729
My variable date_mplayer
simply stores a PHP generated time()
stamp. I need to create an array with a key/value pair which both the key and value are initially the same time stamp from date_mplayer
.
What I've got at the moment:
var md = {date_mplayer:date_mplayer};
localStorage.setItem('date_mplayer', JSON.stringify(md));
If I console.log(localStorage);
I get...
date_mplayer "{"date_mplayer":1427837963}"
What I need should look something like:
date_mplayer "{1427837963:1427837963}"
Background: this is how I will pass function commands to a music player across tabs based on each tab's assigned date. Every X number of seconds the JSON object will be reconstructed with the updated timestamp for the tab's key representation; tabs not updated within a span of time a few seconds longer will have their keys removed (to prevent eternal growth until it hits the browser storage limit).
No frameworks.
Upvotes: 1
Views: 224
Reputation: 34556
Object keys, when written in object literal syntax, are non-dynamic; that is to say, you can't use variables in their place. The key will be named literally what you type there, so:
var foo = 'bar', obj = {foo: foo};
obj.foo; //bar
obj.bar; //undefined
Instead, to set a dynamic key name, you need to set the key via square-bracket syntax after the object has been created, passing the key name as a string:
var foo = 'bar', obj = {};
obj[foo] = foo;
obj.bar; //bar
Upvotes: 1
Reputation: 11052
var md = {};
md[date_mplayer] = date_mplayer;
localStorage.setItem('date_mplayer', JSON.stringify(md));
Upvotes: 1