LocalStorage, JavaScript and objects

I need to store the object in localStorage - and I know that for this I need to convert the object to a string. Everything cool.

My problem is 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 to localStorage. However, when I try to create an object, one value is stored as the name of the variable, not its (numeric) value. Any idea what is going on here?

var siteName = sessionStorage['1']; var siteID = (+sessionStorage['2']); var temp = {siteID:siteName}; alert(typeof siteID); alert(JSON.stringify(temp)); 

The first warning confirms that siteID is indeed a type of number, but the second warning indicates that the variable name (siteID) is stored, not its numeric value.

+4
source share
2 answers

This line:

 var temp = {siteID:siteName}; 

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

If you want the property name to be taken from the siteId variable:

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

Or in ES2015 (aka ES6) you can use the new syntax for computed property names:

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

In JavaScript, you can access / create object properties in two different but equal ways: Using dot notation with the name of a literal property:

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

... or using parenthesized notation and a string:

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

Object initializer keys, such as your var temp = {siteID:siteName}; are always used literally (although they may optionally be in quotation marks); there is no way for an object initializer to have a key taken from a variable instead. Therefore, you need to do this as a two-step process, first create an object, and then set the property.

So if you do

 temp[siteID] = siteName; 

... the number in siteId will be converted to a string and become the name of the property, the value of siteName will be 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].)

+4
source

Change it to.

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

Or, if the typeof test is designed to display the name of a property, you can cancel it.

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

But keep in mind that siteID is considered a line from this point forward.

+2
source

Source: https://habr.com/ru/post/1412784/


All Articles