1

Below is my code snippet

<body ng-app='abc' ng-controller='MainCtrl as ctrl'>
  <div ng-repeat="note in ctrl.notes">
   <span class="label"> {{note[1]}}</span>
   <span class="label"> {{note.label}}</span>
   <span class="status" ng-bind="note.done"></span>
  </div>
</body>

and my notes object contains

self.notes = [
  { id : 1 , label : 'First Note' , done : false, [1]:3, 'string key':4 }, 
  { id : 2 , label : 'Second Note' , done : false, 1:2, 'string key':4 }, 
  { id : 3 , label : 'Done Note' , done : true, 1:2,'string key':4 }, 
  { id : 4 , label : 'Last Note' , done : false, 1:2 , 'string key':4}
];  

I am able to access the label with a.label and a['label'], may I know why these two ways? The second a['label'] only is enough right?

And also if you observe in my notes object, one of the key in first row is [1], I am able to access it with note[1] in html, please let me know how come it is possible?

2 Answers2

0

You can get access by a.label and a['label'] because in Javascript you can get object properties in two ways: object.property and object['property'].

let obj = {
  property: "OK"
}

console.log(obj.property);
console.log(obj['property']);
P.S.
  • 15,970
  • 14
  • 62
  • 86
  • As per this https://stackoverflow.com/questions/20736758/difference-between-dot-notation-and-bracket-notation-in-javascript seems dot notation and [] notation works differently but in angular js both seem to be working same way so no need of two right – Rajesh Kumar Tonukunoori Jun 10 '17 at 10:07
  • @RajeshKumarTonukunoori, that's right, but in this case, where the user is just trying to access the object property with no loops, it seems not to be any differences, doesn't it? – P.S. Jun 10 '17 at 10:13
0

Update:

With reference the article from javascript-object-syntax

Evaluating each dot or bracket expression takes time. If the same property is used multiple times, then it makes more sense to access the property once, and then store the value in a local variable for all future uses.

The following example uses bar many times within a loop. However, instead of wasting time computing the same value over and over, bar is stored in a local variable.

var object = {
  baz: {
    foo: {
      bar: 5
    }
  }
};

var bar = object.baz.foo.bar;

var count = 0;

for (var i = 0; i < 100000; i++) {
  count += bar;
  // better than count += object.baz.foo.bar;
}

If you are accessing a property that is not a valid identifier or if you want to dynamically populate properties from loops or expressions you should use object['property'] otherwise you use object.property.

var obj = {
  'prop1': 'Valid identifier',
  '2prop': 'Invalid identifier'
};
var invalidProp = Object.keys(obj)[1];
console.log(obj.prop1);
// console.log(obj.2prop); // Throws error
console.log(obj['2prop']);
console.log(obj[invalidProp]);
Gangadhar Jannu
  • 4,136
  • 6
  • 29
  • 49