簡體   English   中英

如何在 JavaScript object 文字中使用變量作為鍵?

[英]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 屬性作為變量傳遞給動畫 function。

{ thetop : 10 }是一個有效的對象字面量。 該代碼將創建一個對象,其屬性名為thetop ,其值為 10。以下兩者相同:

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

您可以在每個主流瀏覽器的最新版本中使用這種新語法。

使用ECMAScript 2015 ,您現在可以使用括號符號直接在對象聲明中執行此操作:

var obj = {
  [key]: value
}

其中key可以是返回值的任何類型的表達式(例如變量)。

所以這里你的代碼看起來像:

<something>.stop().animate({
  [thetop]: 10
}, 10)

在用作鍵之前將評估thetop的位置。

ES5 引用說它不應該工作

注意:ES6 的規則已更改: https ://stackoverflow.com/a/2274327/895245

規格:http: //www.ecma-international.org/ecma-262/5.1/#sec-11.1.5

物業名稱:

  • 標識符名稱
  • 字符串字面量
  • 數字字面量

[...]

產品 PropertyName : IdentifierName 的評估如下:

  1. 返回包含與 IdentifierName 相同的字符序列的字符串值。

產生式 PropertyName : StringLiteral 的評估如下:

  1. 返回 StringLiteral 的 SV [字符串值]。

產生式 PropertyName : NumericLiteral 的評估如下:

  1. 令 nbr 為形成 NumericLiteral 值的結果。
  2. 返回到字符串(nbr)。

這意味着:

  • { theTop : 10 }{ 'theTop' : 10 }

    PropertyName theTop是一個IdentifierName ,因此它被轉換為'theTop'字符串值,即 'theTop 'theTop'的字符串值。

  • 不可能用變量鍵編寫對象初始化器(文字)。

    僅有的三個選項是IdentifierName (擴展為字符串文字)、 StringLiteralNumericLiteral (也擴展為字符串)。

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"

希望這可以幫助某人:)

我使用以下內容將具有“動態”名稱的屬性添加到對象:

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}

這只是使用其他答案推薦的所需[]表示法,但代碼行數更少!

在變量周圍添加方括號對我很有用。 嘗試這個

var thetop = 'top';
<something>.stop().animate(
    { [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));

更新:正如評論者指出的那樣,任何支持箭頭函數的 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的解決方案,但在這一點上,您可能會更好地將 Object-creation 分解為它自己的函數而不是強制干擾全部內聯)


自從 OP 十年前提出這個問題以來,這並不重要,而是為了完整起見並證明它是如何准確地回答所述問題,我將在原始上下文中展示這一點:

var thetop = 'top';
<something>.stop().animate(
    ((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);

你也可以這樣嘗試:

 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);

給定代碼:

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);

2020 年更新/示例...

一個更復雜的例子,使用括號和文字......你可能不得不做的事情,例如 vue/axios。 將文字包裹在括號中,所以

[`...`]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}

分配鍵的 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);

如果您希望對象鍵與變量名相同,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
);

這樣您也可以實現所需的輸出

 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 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
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM