How to access object property with invalid characters

ghz 1years ago ⋅ 2276 views

Question

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:newVisits".

If I use the expression {{total.ga:newVisits}}, Angular cannot parse it. Any attempts at escaping the colon to continue has resulted in an error or escaping my expression altogether.

How can I pass {{total.ga:newVisits}} to Angular so that the expression will work properly?

<!doctype html>
  <html ng-app="AnalyticsApp">
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
      <script src="angular-controller.js"></script>
    </head>
    <body ng-controller="AnalyticsCtrl">
      <ul>
        <li ng-repeat="total in result">
          {{total.ga:newVisits}}
        </li>
      </ul>
    </body>
  </html>

Answer

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'