How to access object property with invalid characters

后端 未结 2 1247
-上瘾入骨i
-上瘾入骨i 2020-11-28 16:36

I am writing an Angular app that interfaces with a Google Analytics API already in use. The data returned by Google is prefixed with \"ga:\" as in the example \"ga:newVisit

相关标签:
2条回答
  • 2020-11-28 17:09

    In JavaScript, object properties can be accessed by dot notation or bracket notation. Dot notation is often cleaner, but has restrictions. As you have noticed, your property contains an invalid character and therefore can't be accessed via dot notation. The solution, then, is to access the property using bracket notation like this: total['ga:newVisits'] so that your complete code will be {{total['ga:newVisits']}}. Live demo here (click).

    Another nice feature about bracket notation is that it allows you to use a variable name as a property:

    var myObj {
      bar: '123'
    };
    var foo = 'bar';
    
    console.log(myObj[foo]); //logs '123'
    
    0 讨论(0)
  • 2020-11-28 17:21

    You need to access it as if it were an associative array:

    {{total['ga:newVisits']}}
    
    0 讨论(0)
提交回复
热议问题