2

I have defined an object with properties that have hyphen in their names.

var data = {
  "foo-bar": "value",
  "this-that": "another value"
}

Now I need to reference this property in JS, but both these ways result in syntax error.

console.log( data.foo-bar )

and

console.log( data."foo-bar" )

So my question is. How can I access a property that contains hyphen in the name in JS?


Disclaimer: The server-side functionality require hyphen-naming of the properties and I don't really feel like rewriting somebody else's whole script that takes the input params like this. And yes, I know this current way is not the most clean approach possible.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • [MDN Presents: Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects), and its spin-off [Property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors). – Oka Apr 26 '16 at 12:37

1 Answers1

5

You Could use data["foo-bar"] Instead.

Jenson M John
  • 5,499
  • 5
  • 30
  • 46