Json object with dash (-) character on element name

15,920

Solution 1

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.

Solution 2

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

var video = data.element['data-config'];
Share:
15,920
Pedro Lobito
Author by

Pedro Lobito

[root@lob ~]# man life No manual entry for life "If you can’t fly, run. If you can’t run, walk. If you can’t walk, crawl, but by all means, keep moving.” - Martin Luther King Jr.: Keep Moving

Updated on June 05, 2022

Comments

  • Pedro Lobito
    Pedro Lobito almost 2 years

    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
    Pedro Lobito about 9 years
    That's why I love SO, it works! I'll accept your answer in 10m. tks
  • Pedro Lobito
    Pedro Lobito about 9 years
    Thank you for the explanation.