如何在 JavaScript 对象字面量中使用变量作为键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2274242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use a variable for a key in a JavaScript object literal?
提问by speendo
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.
更清楚地说:目前我无法将 CSS 属性作为变量传递给 animate 函数。
回答by Andy E
{ thetop : 10 }is a valid object literal. The code will create an object with a property named thetopthat has a value of 10. Both the following are the same:
{ thetop : 10 }是一个有效的对象字面量。该代码将创建一个对象,其属性名为thetop10。以下两者相同:
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:
在 ES5 及更早版本中,您不能在对象字面量中使用变量作为属性名称。您唯一的选择是执行以下操作:
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 definesComputedPropertyNameas part of the grammar for object literals, which allows you to write the code like this:
ES6将ComputedPropertyName定义为对象字面量语法的一部分,它允许您编写如下代码:
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.
您可以在每个主流浏览器的最新版本中使用这种新语法。
回答by kube
With ECMAScript 2015you are now able to do it directly in object declaration with the brackets notation:
使用ECMAScript 2015,您现在可以使用括号表示法直接在对象声明中执行此操作:
var obj = {
[key]: value
}
Where keycan be any sort of expression (e.g. a variable) returning a value.
wherekey可以是返回值的任何类型的表达式(例如变量)。
So here your code would look like:
所以这里你的代码看起来像:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetopwill be evaluated before being used as key.
在thetop用作键之前将在哪里评估。
回答by Phil M
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
);
keyis the name of the new property.
key是新属性的名称。
The object of properties passed to animatewill be {left: 20, width: 100, top: 10}
传递给的属性对象animate将是{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!
这只是使用[]其他答案推荐的必需符号,但代码行更少!
回答by Vaishali Venkatesan
Adding square bracket around the variable works good for me. Try this
在变量周围添加方括号对我很有用。尝试这个
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
回答by Dieter Schmitt
I couldn't find a simple exampleabout the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.
我找不到一个简单的例子来说明 ES6 和 ES5 之间的区别,所以我做了一个。两个代码示例都创建了完全相同的对象。但是 ES5 示例也适用于较旧的浏览器(如 IE11),而 ES6 示例则不能。
ES6
ES6
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
ES5
ES5
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
function addObj(obj, key, value) {
obj[key] = value;
return obj;
}
matrix[a] = addObj({}, b, addObj({}, c, d));
回答by mangonights
2020 update/example...
2020 年更新/示例...
A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so
一个更复杂的例子,使用括号和文字……你可能需要做一些事情,例如 vue/axios。将文字包裹在方括号中,所以
[ ` ... ` ]
[ ` ... ` ]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
回答by JamesTheAwesomeDude
I can't believethis hasn't been posted yet: just use arrow-notation with anonymous evaluation!
我不敢相信这还没有发布:只需使用带有匿名评估的箭头符号!
Completelynon-invasive, doesn't mess with the namespace, and it takes just one line:
完全非侵入性,不会弄乱命名空间,并且只需要一行:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
demo:
演示:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
useful in environments that don't support the new {[myKey]: myValue}syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08.
在尚不支持新{[myKey]: myValue}语法的环境中很有用,例如——显然;我刚刚在我的 Web 开发者控制台上验证了它——Firefox 72.0.1,发布于 2020 年 1 月 8 日。
(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)
(我相信您可能会做出一些更强大/可扩展的解决方案或任何涉及巧妙使用 的解决方案reduce,但在这一点上,您可能会通过将 Object-creation 分解为它自己的功能而不是强迫性地干扰它来获得更好的服务全部内联)
not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactlytheanswer to the question as stated, I'll show this in the original context:
这不是问题,因为OP按十年前问过,但为了完整性,并证明它是多么确切的答案,因为说,我会在原来的背景下显示此问题:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
回答by Benny Neugebauer
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:
如您所见,{ thetop : 10 }声明没有使用变量thetop。相反,它使用名为 的键创建一个对象thetop。如果您希望键是变量的值thetop,则必须在 周围使用方括号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:
ES6 中引入了方括号语法。在早期版本的 JavaScript 中,您必须执行以下操作:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
回答by Deepu Reghunath
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>
回答by darcher
ES5 implementation to assign keys is below:
分配键的 ES5 实现如下:
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);

