LocalStorage, JavaScript and Objects

html, javascript, local-storage

Solution

This line:

var temp = {siteID:siteName};

...creates an object containing a property called `siteId` with the value taken from the `siteName` variable.

If you want the property name to be taken from the `siteID` variable instead:

var temp = {};
temp[siteID] = siteName;

Or in ES2015 (aka "ES6") you could use the new computed property name syntax:

// ES2015+ only!
var temp = {[siteId]: siteName};

In JavaScript, you can access/create properties on objects in two different but equal ways: Using dotted notation with a literal property name:

obj.foo = "bar";    // Creates a `foo` property on `obj` with the value `"bar"`

...or using bracketed notation and a string:

obj["foo"] = "bar"; // Does the same thing

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

temp[siteID] = siteName;

...the number in `siteID` will be converted to a string and will become the property name, with the value of `siteName` being the value.

var temp = {};
var key = 1;
temp[key] = "value";
console.log(temp[1]); // "value"
console.log(temp["1"]); // "value"

(Property names are always strings in JavaScript [for now].)

Problem

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.

Original source