1

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

Community
  • 1
  • 1
QuestionOverflow
  • 649
  • 8
  • 20
  • Related: http://stackoverflow.com/q/17574355/4642212 – Sebastian Simon Nov 05 '16 at 01:40
  • FYI, it's called *bracket notation* and *dot notation* (the notation has nothing to do with arrays). And no, this is actually closer related than you think. You have to use bracket notation + a string literal if the property name is not a valid identifier name. Similarly for object literals, you have to use a string literal if the property name is not valid identifier name. Same reason, same solution. – Felix Kling Nov 05 '16 at 01:48

2 Answers2

3

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]: "bbb"
}

console.log(myObject["field-1"], myObject["field-2"])
0.sh
  • 2,659
  • 16
  • 37
2

Inside an object literal, property names can be defined in four ways:

  • as an identifier name (foo)
  • as a number literal (42)
  • as a string literal ('foo bar')
  • as a computed property ([foo + 'bar'])

field-1 is neither of those. It's not an identifier because the character - is not valid in identifier names. It's relatively easy to know whether something is a valid identifier name: If it's not a keyword and not a valid variable name, it's not a valid identifier name. That is, since it's invalid to declare the variable

var field-1 = 42;

you cannot use it in a object literal either.

You have to use a string literal instead. A string literal can contain any character sequence:

myObject = {'field-1':"aaa"};
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143