tomloprod tomloprod - 6 months ago 55
AngularJS Question

Computed property names. "gulp-angular-filesort : unexpected token ["

I need to asign a JSON property name dynamically, so I tried with computed property names:

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

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


...but, when I run
gulp serve
I get the next error:

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


error gulp-angular-filesort

I tried too with bracket notation:

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

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


But I get the same error... So I tried to try luck with dot dotation:

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

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


And I get a similar error:

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





Obviously... Something is escaping me. You know any alternative or solution?





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


Answer

You can add the dynamicNameProperty after the 'element' object is created:

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

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

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