Javascript 关联数组声明单行中的动态键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17840553/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:49:11  来源:igfitidea点击:

Dynamic keys in Javascript associative array declaration one-liner

javascript

提问by ajwood

I would expect the following three associative arrays to be identical:

我希望以下三个关联数组是相同的:

arr1 = { "dynamic":"foo", "bar":"baz" };

key = "dynamic";    
arr2 = { key:"foo", "bar":"baz" };

arr3 = {};
arr3[key] = "foo";
arr3["bar"] = "baz";

In the above examples, arr1and arr3are the same, but arr2is different.

在上面的例子中,arr1arr3是相同的,但是arr2是不同的。

Is it possible to use dynamic keys in the declaration of a javascript associative array?

是否可以在 javascript 关联数组的声明中使用动态键?

采纳答案by ThiefMaster

Only the []syntax works for dynamic keys. You cannot use them in a literal. So your answer is no, it's not possible.

只有[]语法适用于动态键。你不能在文字中使用它们。所以你的答案是否定的,这是不可能的。

But you can use a literal to create all the static keys and then add the dynamic ones using the []syntax. That's usually prettier than using the .or []notation for allelements.

但是您可以使用文字来创建所有静态键,然后使用[]语法添加动态键。这通常比对所有元素使用.or[]符号更漂亮。

回答by Brian

It is nowpossible to use dynamic keys in the declaration of a javascript object, in any browser/platform that supports ES6 literal shorthands:

这是现在可以在JavaScript对象的声明使用动态密钥,在任何浏览器/平台,支持ES6文字速记:

key = "dynamic";    
arr2 = {
    [key]: "foo",  // "dynamic": "foo"
    "bar": "baz"
};

回答by Ramasamy Kasi

I found a solution for this.

我为此找到了解决方案。

Do as following:

执行以下操作:

var field='name';

var ourVar={};

ourVar[field] = 'Somethig';

Source: Javascript: variable as array key

来源:Javascript:变量作为数组键

回答by Phil M

Since you asked for a one liner, try this:

既然你要求单衬,试试这个:

var key = 'dynamic', obj = (function(o) { o[key]='foo'; return o;})({bar: 'baz'});

This will make objequal to {bar: "baz", dynamic: "foo"}

这将obj等于{bar: "baz", dynamic: "foo"}

回答by Vladimir Monsanto

var originalObj = {};//some data here


function addKeyValuePair(originalObj,key,value){
    originalObj = {...originalObj,[key]:value}
};