How to use a variable for a key in a JavaScript object literal?
Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
javascript jquery variables properties object-literal
add a comment |
Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
javascript jquery variables properties object-literal
1
see also: create object using variables for property name
– Bergi
Aug 16 '14 at 19:48
1
see also: creating object with dynamic keys
– Bergi
Nov 18 '14 at 5:50
add a comment |
Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
javascript jquery variables properties object-literal
Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
javascript jquery variables properties object-literal
javascript jquery variables properties object-literal
edited Mar 16 '18 at 10:52
Ciro Santilli 新疆改造中心 六四事件 法轮功
146k34557472
146k34557472
asked Feb 16 '10 at 16:05
speendospeendo
4,689135493
4,689135493
1
see also: create object using variables for property name
– Bergi
Aug 16 '14 at 19:48
1
see also: creating object with dynamic keys
– Bergi
Nov 18 '14 at 5:50
add a comment |
1
see also: create object using variables for property name
– Bergi
Aug 16 '14 at 19:48
1
see also: creating object with dynamic keys
– Bergi
Nov 18 '14 at 5:50
1
1
see also: create object using variables for property name
– Bergi
Aug 16 '14 at 19:48
see also: create object using variables for property name
– Bergi
Aug 16 '14 at 19:48
1
1
see also: creating object with dynamic keys
– Bergi
Nov 18 '14 at 5:50
see also: creating object with dynamic keys
– Bergi
Nov 18 '14 at 5:50
add a comment |
11 Answers
11
active
oldest
votes
{ 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.
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
3
@Marcel:eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, buteval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage ofeval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx
– Andy E
Feb 16 '10 at 16:44
2
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in{[key] : "value"}
, if key was null, it would give{ null: "value"}
, whereas I'd like the result to be{}
– wasabigeek
Mar 10 '18 at 14:52
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
add a comment |
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop
will be replaced by the variable value.
add a comment |
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
- IdentifierName
- StringLiteral
- NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
- Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
- Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
- Let nbr be the result of forming the value of the NumericLiteral.
- Return ToString(nbr).
This means that:
{ theTop : 10 }
is the exact same as{ 'theTop' : 10 }
The
PropertyName
theTop
is anIdentifierName
, so it gets converted to the'theTop'
string value, which is the string value of'theTop'
.
It is not possible to write object initializers (literals) with variable keys.
The only three options are
IdentifierName
(expands to string literal),StringLiteral
, andNumericLiteral
(also expands to a string).
3
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
3
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surelythetop
is anIdentifierName
, so why does it not work? That question is still open.
– Bergi
Aug 3 '15 at 13:10
1
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write{a:1}.a
, soa
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
|
show 1 more comment
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
is the name of the new property.
The object of properties passed to animate
will be {left: 20, width: 100, top: 10}
This is just using the required notation as recommended by the other answers, but with fewer lines of code!
add a comment |
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
add a comment |
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 }
declaration doesn't make use of the variable thetop
. Instead it creates an object with a key named thetop
. If you want the key to be the value of the variable thetop
, then you will have to use square brackets around thetop
:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
add a comment |
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
add a comment |
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
add a comment |
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
add a comment |
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
add a comment |
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2274242%2fhow-to-use-a-variable-for-a-key-in-a-javascript-object-literal%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
{ 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.
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
3
@Marcel:eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, buteval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage ofeval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx
– Andy E
Feb 16 '10 at 16:44
2
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in{[key] : "value"}
, if key was null, it would give{ null: "value"}
, whereas I'd like the result to be{}
– wasabigeek
Mar 10 '18 at 14:52
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
add a comment |
{ 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.
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
3
@Marcel:eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, buteval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage ofeval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx
– Andy E
Feb 16 '10 at 16:44
2
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in{[key] : "value"}
, if key was null, it would give{ null: "value"}
, whereas I'd like the result to be{}
– wasabigeek
Mar 10 '18 at 14:52
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
add a comment |
{ 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.
{ 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.
edited Dec 13 '17 at 12:12
answered Feb 16 '10 at 16:15
Andy EAndy E
266k67416419
266k67416419
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
3
@Marcel:eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, buteval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage ofeval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx
– Andy E
Feb 16 '10 at 16:44
2
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in{[key] : "value"}
, if key was null, it would give{ null: "value"}
, whereas I'd like the result to be{}
– wasabigeek
Mar 10 '18 at 14:52
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
add a comment |
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
3
@Marcel:eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, buteval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage ofeval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx
– Andy E
Feb 16 '10 at 16:44
2
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in{[key] : "value"}
, if key was null, it would give{ null: "value"}
, whereas I'd like the result to be{}
– wasabigeek
Mar 10 '18 at 14:52
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)
– speendo
Feb 16 '10 at 16:38
3
3
@Marcel:
eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, but eval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage of eval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx– Andy E
Feb 16 '10 at 16:44
@Marcel:
eval()
wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, but eval()
really shouldn't be used for such things. There's an excellent article on correct and incorrect usage of eval
: blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx– Andy E
Feb 16 '10 at 16:44
2
2
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.
– Alexei Levenkov
Feb 26 '15 at 1:59
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in
{[key] : "value"}
, if key was null, it would give { null: "value"}
, whereas I'd like the result to be {}
– wasabigeek
Mar 10 '18 at 14:52
for ES6, is there a way to leave out the property if the key is null/undefined? For example, in
{[key] : "value"}
, if key was null, it would give { null: "value"}
, whereas I'd like the result to be {}
– wasabigeek
Mar 10 '18 at 14:52
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
wonderful solution, but why you know so much, even reading the whole specification could not get point:(
– hugemeow
Apr 13 '18 at 22:41
add a comment |
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop
will be replaced by the variable value.
add a comment |
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop
will be replaced by the variable value.
add a comment |
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop
will be replaced by the variable value.
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop
will be replaced by the variable value.
edited Oct 18 '17 at 8:14
answered Mar 15 '16 at 23:17
kubekube
5,19932135
5,19932135
add a comment |
add a comment |
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
- IdentifierName
- StringLiteral
- NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
- Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
- Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
- Let nbr be the result of forming the value of the NumericLiteral.
- Return ToString(nbr).
This means that:
{ theTop : 10 }
is the exact same as{ 'theTop' : 10 }
The
PropertyName
theTop
is anIdentifierName
, so it gets converted to the'theTop'
string value, which is the string value of'theTop'
.
It is not possible to write object initializers (literals) with variable keys.
The only three options are
IdentifierName
(expands to string literal),StringLiteral
, andNumericLiteral
(also expands to a string).
3
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
3
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surelythetop
is anIdentifierName
, so why does it not work? That question is still open.
– Bergi
Aug 3 '15 at 13:10
1
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write{a:1}.a
, soa
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
|
show 1 more comment
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
- IdentifierName
- StringLiteral
- NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
- Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
- Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
- Let nbr be the result of forming the value of the NumericLiteral.
- Return ToString(nbr).
This means that:
{ theTop : 10 }
is the exact same as{ 'theTop' : 10 }
The
PropertyName
theTop
is anIdentifierName
, so it gets converted to the'theTop'
string value, which is the string value of'theTop'
.
It is not possible to write object initializers (literals) with variable keys.
The only three options are
IdentifierName
(expands to string literal),StringLiteral
, andNumericLiteral
(also expands to a string).
3
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
3
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surelythetop
is anIdentifierName
, so why does it not work? That question is still open.
– Bergi
Aug 3 '15 at 13:10
1
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write{a:1}.a
, soa
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
|
show 1 more comment
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
- IdentifierName
- StringLiteral
- NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
- Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
- Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
- Let nbr be the result of forming the value of the NumericLiteral.
- Return ToString(nbr).
This means that:
{ theTop : 10 }
is the exact same as{ 'theTop' : 10 }
The
PropertyName
theTop
is anIdentifierName
, so it gets converted to the'theTop'
string value, which is the string value of'theTop'
.
It is not possible to write object initializers (literals) with variable keys.
The only three options are
IdentifierName
(expands to string literal),StringLiteral
, andNumericLiteral
(also expands to a string).
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
- IdentifierName
- StringLiteral
- NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
- Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
- Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
- Let nbr be the result of forming the value of the NumericLiteral.
- Return ToString(nbr).
This means that:
{ theTop : 10 }
is the exact same as{ 'theTop' : 10 }
The
PropertyName
theTop
is anIdentifierName
, so it gets converted to the'theTop'
string value, which is the string value of'theTop'
.
It is not possible to write object initializers (literals) with variable keys.
The only three options are
IdentifierName
(expands to string literal),StringLiteral
, andNumericLiteral
(also expands to a string).
edited 17 hours ago
answered Jun 16 '14 at 12:35
Ciro Santilli 新疆改造中心 六四事件 法轮功Ciro Santilli 新疆改造中心 六四事件 法轮功
146k34557472
146k34557472
3
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
3
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surelythetop
is anIdentifierName
, so why does it not work? That question is still open.
– Bergi
Aug 3 '15 at 13:10
1
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write{a:1}.a
, soa
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
|
show 1 more comment
3
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
3
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surelythetop
is anIdentifierName
, so why does it not work? That question is still open.
– Bergi
Aug 3 '15 at 13:10
1
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write{a:1}.a
, soa
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
3
3
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 14 '15 at 15:32
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)
– Bergi
Aug 2 '15 at 21:22
3
3
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?
– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 5:17
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surely
thetop
is an IdentifierName
, so why does it not work? That question is still open.– Bergi
Aug 3 '15 at 13:10
Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surely
thetop
is an IdentifierName
, so why does it not work? That question is still open.– Bergi
Aug 3 '15 at 13:10
1
1
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write
{a:1}.a
, so a
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write
{a:1}.a
, so a
clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.– Ciro Santilli 新疆改造中心 六四事件 法轮功
Aug 3 '15 at 14:23
|
show 1 more comment
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
is the name of the new property.
The object of properties passed to animate
will be {left: 20, width: 100, top: 10}
This is just using the required notation as recommended by the other answers, but with fewer lines of code!
add a comment |
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
is the name of the new property.
The object of properties passed to animate
will be {left: 20, width: 100, top: 10}
This is just using the required notation as recommended by the other answers, but with fewer lines of code!
add a comment |
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
is the name of the new property.
The object of properties passed to animate
will be {left: 20, width: 100, top: 10}
This is just using the required notation as recommended by the other answers, but with fewer lines of code!
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
is the name of the new property.
The object of properties passed to animate
will be {left: 20, width: 100, top: 10}
This is just using the required notation as recommended by the other answers, but with fewer lines of code!
answered Jan 10 '14 at 10:42
Phil MPhil M
8201710
8201710
add a comment |
add a comment |
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
add a comment |
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
add a comment |
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
answered May 13 '17 at 9:30
Vaishali Vaishali
10112
10112
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
add a comment |
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.
– Oliver
May 13 '17 at 9:57
add a comment |
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 }
declaration doesn't make use of the variable thetop
. Instead it creates an object with a key named thetop
. If you want the key to be the value of the variable thetop
, then you will have to use square brackets around thetop
:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
add a comment |
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 }
declaration doesn't make use of the variable thetop
. Instead it creates an object with a key named thetop
. If you want the key to be the value of the variable thetop
, then you will have to use square brackets around thetop
:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
add a comment |
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 }
declaration doesn't make use of the variable thetop
. Instead it creates an object with a key named thetop
. If you want the key to be the value of the variable thetop
, then you will have to use square brackets around thetop
:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 }
declaration doesn't make use of the variable thetop
. Instead it creates an object with a key named thetop
. If you want the key to be the value of the variable thetop
, then you will have to use square brackets around thetop
:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
answered Oct 9 '17 at 18:29
Benny NeugebauerBenny Neugebauer
28.2k16150151
28.2k16150151
add a comment |
add a comment |
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
add a comment |
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
add a comment |
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
answered Mar 28 '18 at 10:03
Deepu ReghunathDeepu Reghunath
1,609622
1,609622
add a comment |
add a comment |
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
add a comment |
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
add a comment |
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = ;
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
edited Oct 3 '18 at 0:15
answered Oct 2 '18 at 2:43
darcherdarcher
1,56321626
1,56321626
add a comment |
add a comment |
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
add a comment |
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
add a comment |
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
edited Oct 9 '18 at 14:25
answered Oct 9 '18 at 0:01
sh32mysh32my
11
11
add a comment |
add a comment |
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
add a comment |
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
add a comment |
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
answered Feb 13 at 8:01
ROROROORORORROROROOROROR
373824
373824
add a comment |
add a comment |
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
add a comment |
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
add a comment |
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
answered Feb 13 at 12:19
Yury LaykovYury Laykov
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2274242%2fhow-to-use-a-variable-for-a-key-in-a-javascript-object-literal%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
see also: create object using variables for property name
– Bergi
Aug 16 '14 at 19:48
1
see also: creating object with dynamic keys
– Bergi
Nov 18 '14 at 5:50