5

I'm parsing a json object that contains an element named data-config.

ex:

var video = data.element.data-config;

Whenever I parse this element I'm getting this error:

ReferenceError: config is not defined

The ReferenceError doesn't mention data-config but simply config.
Any idea why I'm getting this error? Is this related with the dash (-) character?

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Does this answer your question? [How do I reference a javascript object property with a hyphen in it?](https://stackoverflow.com/questions/7122609/how-do-i-reference-a-javascript-object-property-with-a-hyphen-in-it) – Henke Jan 29 '21 at 10:32

2 Answers2

18

Valid Characters

In general JavaScript, variable/function names can't contain -. They can only contain letters, $, and _ (Underscore)

So...

The error is coming because it's parsing:

var video is equal to data.element.data(valid) minus config

Solution

Because variables can't contain dashes, you need to use what I'm going to call String/Bracket Notation

data.element['data-config']

If you need to do more then one, do

data.element['data-config']['child']

I don't recommend using String/Bracket Notation when you don't have to, it's better practice.

Community
  • 1
  • 1
Downgoat
  • 13,771
  • 5
  • 46
  • 69
1

You have to use [] notation when object properties contain special characters

var video = data.element['data-config'];
charlietfl
  • 170,828
  • 13
  • 121
  • 150