QuestionOverflow QuestionOverflow - 1 year ago 59
Javascript Question

How can I statically declare a Javascript object instance (a.k.a "associative array") whose property names (a.k.a keys) contain dashes?

I want to statically declare a Javascript object (sometimes referred to as "associative array" when used as such) whose property names ("keys") contain dashes?

Without dashes (works):

myObject = {field_1:"aaa", field_2:"bbb"};

With dashes (results in syntax error):

myObject = {field-1:"aaa", field-2:"bbb"};

(And yes, I'm fully aware that such properties containing dashes can only be referenced by using "bracket notation" rather than "dot notation", but that's a completely other story, I'm only talking about the case of static declaration of such objects here.)

Answer Source

you have to wrap the property names in quote to read "field-1" as a string.

var myObject = {"field-1":"aaa", "field-2":"bbb"}
console.log(myObject["field-1"], myObject["field-2"])

//computed properties
var name1 = "field-1"
var name2 = "field-2"

var myObject = {
     [name1]: "aaa",
     [name2]: "bbbb"

console.log(myObject["field-1"], myObject["field-2"])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download