2

My response object has a field called "50", so right now I'm trying to access and save that data doing something like this:

var thing = $scope.data.array[0].50;

However I'm getting an error on the console when I simply reload the page with the function not even running. When I get rid of the 50, everything is fine. There is indeed a field called "50" inside the $scope.data.array[0] and I do not have access to change the response. Is there something wrong with this because the field is called "50" and maybe JS is interrupting that as a number instead??

Also when I changed "50" to something random like "af", then I get no errors on refresh.

this doesn't work var thing = $scope.data.array[0].50;

this works var thing = $scope.data.array[0].af;

Yan
  • 59
  • 6

1 Answers1

3

The following should work if your first element of the array has a property called "50".

var thing = $scope.data.array[0]["50"];

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

Syntax
object.property
object["property"]

JavaScript objects are also associative arrays (hashes). Using these you can associate a key string with a value string as shown in the example above.

The reason as to why you don't get an error when accessing $scope.data.array[0].af; is because "af" is valid identifier for a property. Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence.

For all other property names, you must use bracket notation.

Dayan
  • 7,634
  • 11
  • 49
  • 76