I need to store an object in localStorage – and I know that in order to do so, I have to convert the object into a string. All cool.
My problem is in actually creating the object in the first place: I have two values in sessionStorage that need to be added to the object which is then passed into localStorage. However, when I try to create the object, one value is being stored as the variable name rather than its (numeric) value. Any idea whats going on here?
var siteName = sessionStorage['1'];
var siteID = (+sessionStorage['2']);
var temp = {siteID:siteName};
alert(typeof siteID);
alert(JSON.stringify(temp));
The first alert confirms that siteID is indeed a number type, but the second alert shows that the variable name (siteID) is stored rather than its numeric value.
This line:
…creates an object containing a property called
siteIdwith the value taken from thesiteNamevariable.If you want the property name to be taken from the
siteIDvariable instead:Or in ES2015 (aka “ES6”) you could use the new computed property name syntax:
In JavaScript, you can access/create properties on objects in two different but equal ways: Using dotted notation with a literal property name:
…or using bracketed notation and a string:
The keys in object initializers like your
var temp = {siteID:siteName};are always used literally (although they can optionally be in quotes); there’s no way with an object initializer to have a key taken from a variable instead. So you have to do it as a two-step process, first create the object, then set the property.So, if you do
…the number in
siteIDwill be converted to a string and will become the property name, with the value ofsiteNamebeing the value.(Property names are always strings in JavaScript [for now].)