2016-05-20 40 views
3

我需要ASIGN一個JSON屬性名動態,所以我試着用computed property names計算屬性名稱。 「吞掉-角文件排序:意外的標記[」

var dynamicNameProperty = (!irrelevantCondition) ? "name1" : "name2"; 

var element = { 
    "oneStaticNameProp":"Hi!", 
    [dynamicProperty] : "Oh oh... This produces an error." 
}; 

...但是,當我運行gulp serve我得到了一個錯誤:

Error in parsing: "main\templates\dashboard\dashboard.controller.js", Line 160: Unexpected token [ 

error gulp-angular-filesort

bracket notation嘗試過:

var dynamicNameProperty["name"] = (!irrelevantCondition) ? "name1" : "name2"; 

var element = { 
    "oneStaticNameProp":"Hi!", 
    dynamicNameProperty["name"] : "Oh oh... This produces an error too." 
}; 

,但我得到了同樣的錯誤......於是,我就嘗試用dot dotation運氣:

var myObject = { 
    dynamicNameProperty: (!irrelevantCondition) ? "name1" : "name2" 
}; 

var element = { 
    "oneStaticNameProp":"Hi!", 
    myObject.dynamicNameProperty : "Oh oh... This produces an error too." 
}; 

我也得到了類似的錯誤:

Error in parsing: "main\templates\dashboard\dashboard.controller.js", Line 160: Unexpected token . 

顯然......有東西在逃避我。你知道任何替代或解決方案嗎?


WARNING: This is only an example of my problem: I can not and I do not want just use an if statement for the two states of dynamicNameProperty

+0

我想我的問題需要標題的變化... – tomloprod

回答

3

您可以添加dynamicNameProperty 創建 '元素' 對象後:

var dynamicNameProperty = (!irrelevantCondition) ? "name1" : "name2"; 

var element = { 
    "oneStaticNameProp":"Hi!" 
}; 

element[dynamicNameProperty] = "Yay....no error here!"; 
+0

哇!我知道有些東西能逃脫我:)這是我唯​​一沒有嘗試的東西!謝謝。 – tomloprod