0

In an AngularJS app, I have an object stored in data returned from $http that looks something like this:

[{"var1":"1","var2":"2","var3":"3"}]

I want to be able to get the value of "var2".

I thought this would be easy:

$scope.myObj = data;

$scope.myVar = $scope.myObj.var2;  //$scope.myvar should "2"

Instead, $scope.myObj returns undefined

how can I access the value of var2?

6
  • If $scope.myObj returns undefined, you DONT have the data yet. Paste the code for help. Commented Jan 7, 2015 at 16:05
  • 3
    Seems like data is array, if it is always of size 1 array then do $scope.myObj = data[0] Commented Jan 7, 2015 at 16:05
  • @user013948 it's not empty. console.log($scope.myvar) shows [object Object] and, in HTML, {{myVar}} displays [{"var1":"1","var2":"2","var3":"3"}] Commented Jan 7, 2015 at 16:12
  • Try $scope.myVar.var2 Commented Jan 7, 2015 at 16:15
  • @PSL Bingo! It was an array, even though angular.isObject() returned true. Please enter this as an answer and I will mark it as CORRECT!! Commented Jan 7, 2015 at 16:33

1 Answer 1

1

It looks like in your case data is an array. And if it is always of size -1 array just do:

$scope.myObj = data[0]; //Add any necessary null checks

Modify your logic accordingly by looping through the array if it is of size > 1.

angular.isObject() returns true because array is also an object.

You can use angular.isArray(obj) before checking isObject to make sure you filter out arrays as is. If you get mixed data i.e sometimes object, sometimes array of size-1 with the same object you could also do:- $scope.myObj = [].concat(data)[0].

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.