简体   繁体   English

从$ http返回的AngularJS对象-如何获取键/值对

[英]AngularJS object returned from $http - how to get key/value pairs

In an AngularJS app, I have an object stored in data returned from $http that looks something like this: 在AngularJS应用中,我有一个对象存储在$http返回的data ,该对象看起来像这样:

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

I want to be able to get the value of "var2" . 我希望能够获取"var2"的值。

I thought this would be easy: 我认为这很容易:

$scope.myObj = data;

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

Instead, $scope.myObj returns undefined 而是$ scope.myObj返回undefined

how can I access the value of var2? 如何访问var2的值?

It looks like in your case data is an array. 在您的情况下,数据似乎是一个数组。 And if it is always of size -1 array just do: 如果它总是大小为-1数组,请执行以下操作:

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

Modify your logic accordingly by looping through the array if it is of size > 1. 如果大小> 1,则通过遍历数组来相应地修改逻辑。

angular.isObject() returns true because array is also an object. angular.isObject()返回true,因为array也是一个对象。

You can use angular.isArray(obj) before checking isObject to make sure you filter out arrays as is. 在检查isObject之前,可以使用angular.isArray(obj)来确保按原样过滤出数组。 If you get mixed data ie sometimes object, sometimes array of size-1 with the same object you could also do:- $scope.myObj = [].concat(data)[0] . 如果您得到混合数据,即有时是对象,有时是大小为1的数组与同一对象,则您也可以这样做:- $scope.myObj = [].concat(data)[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM