提问人:speendo 提问时间:2/17/2010 最后编辑:Ivarspeendo 更新时间:12/6/2022 访问量:311632
如何在JavaScript对象文字中将变量用于键?
How to use a variable for a key in a JavaScript object literal?
问:
为什么以下方法有效?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
而这不起作用:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
更清楚地说:目前我无法将 CSS 属性作为变量传递给 animate 函数。
答:
{ thetop : 10 }
是有效的对象文本。该代码将创建一个对象,其属性名为值为 10。以下两者都是相同的:thetop
obj = { thetop : 10 };
obj = { "thetop" : 10 };
在 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 将 ComputedPropertyName 定义为对象文字语法的一部分,它允许您编写如下代码:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
您可以在每个主流浏览器的最新版本中使用这种新语法。
评论
eval()
eval()
eval
{[key] : "value"}
{ null: "value"}
{}
我使用以下方法将具有“动态”名称的属性添加到对象:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
是新属性的名称。
传递给的属性的对象将是animate
{left: 20, width: 100, top: 10}
这只是使用其他答案推荐的所需符号,但代码行数更少![]
ES5 报价说它不应该工作
注意:ES6 的规则已更改:https://stackoverflow.com/a/2274327/895245
规格: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
属性名称:
- 标识符名称
- StringLiteral(字符串文字)
- NumericLiteral
[...]
生产 PropertyName : IdentifierName 的计算方式如下:
- 返回 String 值,该值包含与 IdentifierName 相同的字符序列。
生产 PropertyName : StringLiteral 的计算方式如下:
- 返回 StringLiteral 的 SV [String 值]。
生产 PropertyName : NumericLiteral 的计算方式如下:
- 设 nbr 是形成 NumericLiteral 值的结果。
- 返回 ToString(nbr)。
这意味着:
{ theTop : 10 }
与{ 'theTop' : 10 }
是一个 ,因此它被转换为字符串值,即 的字符串值。
PropertyName
theTop
IdentifierName
'theTop'
'theTop'
不能使用变量键编写对象初始值设定项(文本)。
仅有的三个选项是(扩展为字符串文本)、和(也扩展为字符串)。
IdentifierName
StringLiteral
NumericLiteral
评论
thetop
IdentifierName
{a:1}.a
a
在 ECMAScript 2015 中,您现在可以直接在对象声明中使用括号表示法来执行此操作:
var obj = {
[key]: value
}
其中可以是返回值的任何类型的表达式(例如变量)。key
因此,您的代码如下所示:
<something>.stop().animate({
[thetop]: 10
}, 10)
在用作密钥之前将评估 Where。thetop
在变量周围添加方括号对我有好处。试试这个
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
评论
给定代码:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
译本:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
如您所见,声明没有使用变量 。相反,它会创建一个具有名为 的键的对象。如果您希望键是变量的值,则必须在以下两边使用方括号:{ thetop : 10 }
thetop
thetop
thetop
thetop
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
方括号语法已在 ES6 中引入。在早期版本的 JavaScript 中,您必须执行以下操作:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
评论
obj['' + thetop]
可以替换为 .它会自动字符串化,除非它是一个符号。obj[thetop]
这样,您也可以获得所需的输出
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>
分配密钥的 ES5 实现如下:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
我附上了一个用于转换为裸对象的片段。
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 执行以下操作:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
或提取到函数:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
如果您希望对象键与变量名称相同,ES 2015 中有一个简写。ECMAScript 2015 中的新符号
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
你可以这样做:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
我找不到关于 ES6 和 ES5 之间差异的简单示例,所以我做了一个。这两个代码示例创建完全相同的对象。但是 ES5 示例也适用于较旧的浏览器(如 IE11),而 ES6 示例则不行。
ES6 (美)
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
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));
您也可以尝试这样做:
const arr = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
const res = arr.map(value => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
评论
更新:正如一位评论者指出的那样,任何支持箭头函数的 JavaScript 版本也将支持 ,所以这个答案没有实际的用例(事实上,它可能会在一些奇怪的极端情况下中断)。({[myKey]:myValue})
不要使用下面列出的方法。
我简直不敢相信这还没有发布:只需使用带有匿名评估的箭头函数!
完全非侵入性,不会弄乱命名空间,只需要一行:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
演示:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
在尚不支持新的 我纠正了;只要把东西括在括号里,它就可以工作了。{[myKey]: myValue}
语法的环境中很有用,例如——显然;我刚刚在我的 Web 开发人员控制台上验证了它——Firefox 72.0.1,发布于 2020 年 1 月 8 日。
(我敢肯定,你可能会做出一些更强大/可扩展的解决方案,或者任何涉及巧妙使用 ,但在这一点上,你可能会更好地将对象创建分解成它自己的函数,而不是强迫性地将其全部内联)reduce
自从 OP 十年前提出这个问题以来,这并不重要,但为了完整起见并证明它如何准确地回答上述问题,我将在原始上下文中展示这一点:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
评论
({ [myKey]: myValue })
2020 更新/示例...
一个更复杂的例子,使用括号和文字......例如,使用 Vue/Axios,您可能必须执行一些操作。将文字括在括号中,因此
[ ` ... ` ]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
ES6 [美] / 2020
如果您尝试使用来自任何其他来源的“key:value”将数据推送到对象,则可以使用如下方法:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
希望这对某人有所帮助:)
评论
obj[`some-prefix-${key}`] = value
如果有人希望享受修改关键变量的灵活性,也有效。结果是{ some-prefix-foo: "bar" }
下一个:不能从静态上下文中引用非静态变量
评论