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:
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";
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].)
source share