Using variable *name* as property name in object literal
It is part of ES6, check for shorthand properties http://es6-features.org/#PropertyShorthand
Variable as property name in JavaScript object literal
You could use an object and assign with the incremented index.
var data = {}, j;
for (i = 0; i < 2; i++) { j = i + 1; data[j] = { epg: {} }; data[j].epg['title' + j] = ''; data[j].epg['start' + j] = ''; data[j].epg['stop' + j] = ''; data[j].epg['percent' + j] = ''; data[j].epg['step' + j] = '';}
console.log(data);
Use variable for property name in JavaScript literal?
You're confusing accessing with assigning.
// Assigns a variable named 'value' with a value of 'New Value'.
var value = "New value";
// Creates a variable named 'table' as a blank Object.
var table = new Object(); // Alternatively - table = {};
// Attempts to access "New Value" from object "table" which returns undefined.
var newValue = table[value];
If you want to assign properties to an object you do so like this:
// Assumes table is still an object.
table['key'] = 'value';
// Note that I almost _always_ opt for the variable['key'] notation over
// the variable.key notation because it allows you to use keys
// that would otherwise not be valid as identifiers.
table['Some Key'] = 'Some Value'; // This works.
table.Some Key = 'Some Value'; // This does not.
Later, when you want to retrieve that value and store it in a new variable, that's when you do this:
var newVariable = table['key'];
Hopefully that clarifies some. Please let me know if I can expand on any part of it.
How to use a variable for a key in a JavaScript object literal?
{ thetop : 10 }
is a valid object literal. The code will create an object with a property named thetop
that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
var thetop = "top";
// create the object literal
var aniArgs = {};
// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;
// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
You can use this new syntax in the latest versions of each mainstream browser.
create object using variables for property name
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):
Create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify
method.
Inline object literal with a variable property
Why does Javascript syntax not support inline object literals with a variable property?
You seem to be asking about variable properties, yet your examples do not use variables. Specifically, this example will work just fine.
f({ 'some key' : 1})
However, if you actually did want to use a variable without first creating the object, ECMAScript 6 now allows this.
So if this is your variable:
var my_variable = 'some key';
You can now use square brackets around the property name in the object literal, and it will use the value of the expression you provide:
var o = {[my_variable]: 1};
The o
object will have a property named "some key"
. This only works in the implementations that support this syntax of course.
Using Variable for Property Name of Object - Javascript
To set variables as key names you have to use bracket notation;
console.log(first); // returns 'name'
var obj = {};
obj[first] = value;
objArr[key] = obj; // no longer a problem
Sorry it's more verbose :(
Edit;
In ES6 you can now use computed-property-names;
const key = 'name';
const value = 'james';
const obj = {
[key]: value
};
Passing a variable as a property name
You can use bracket notation to set the property name of an object. See chrome.storage.local.set using a variable key name, chrome.storage
var value = "123";
var name = "abc";
var obj = {};
obj[name] = value;
chrome.storage.local.set(obj);
How do I use a variable for a property name in an object initializer/literal?
There are two answers to this question:
The answer for ECMAScript5 (ES5) and below
The answer for ECMAScript6 (ES6) and up
The answer for ECMAScript5 (ES5) and below
You can't do it with a property initializer, the part before the :
is always used literally, it's not an expression that gets evaluated.
To create a property with a name from a variable, you have to create the object separately, then set the property using brackets notation (and then pass the object to the function):
function SaveToStore(thisObjName) {
var thisObj = $('#'+thisObjName), args = {};
args[thisObjName] = thisObj.is(':checked');
chrome.storage.sync.set(args);
}
The answer for ECMAScript6 (ES6) and up
You can do that with a computed property name in the property initializer. It looks like this:
function SaveToStore(thisObjName) {
var thisObj = $('#'+thisObjName);
chrome.storage.sync.set({
[thisObjName]: thisObj.is(':checked') // ES6 syntax! Not currently widespread
});
}
Note the []
around the thisObjName
on the left-hand side of the :
— those indicate that what's inside is an expression, not a literal.
Related Topics
How to Make a Promise from Settimeout
How to Submit a Form Using JavaScript
Create Object from Class Name in Javasscript Ecmascript 6
Browsers, Time Zones, Chrome 67 Error (Historic Timezone Changes)
Node.Js on Multi-Core MAChines
Jquery Load More Data on Scroll
How to Get Form Data with JavaScript/Jquery
Convert String with Commas to Array
How to Download a File with Angular2 or Greater
Truncate Number to Two Decimal Places Without Rounding
Open a New Tab in the Background
What Is the Meaning of the 'G' Flag in Regular Expressions
How to Render an Array of Objects in React
Get Global Variable Dynamically by Name String in JavaScript