从json数组中的键检索值

时间:2019-04-04 01:15:48

标签: arrays json angularjs

我有一个angularjs函数,它包含一个如下的json数组。

$scope.userDetails = [{
name: 'Anil Singh',
age: 30
 }, {
name: 'Reena Singh',
age: 25
}];

我需要获取年龄密钥的所有值。这是我的代码。

$scope.getAge = function()
{
    $scope.userDetails = [{
                     name: 'Anil Singh',
                     age: 30
                      }, {
                     name: 'Reena Singh',
                     age: 25
                     }];
    for(var i=0;i< $scope.userDetails.length;i++)
    {
        console.log("This is age"+$scope.userDetails[i].age);
    }
};

但是当我检查控制台日志时,它显示为未定义值。

2 个答案:

答案 0 :(得分:0)

演示

var app = angular.module('testApp',[])
app.controller('testCtrl',function($scope){
$scope.getAge = function()
{
$scope.userDetails = [{
                     name: 'Anil Singh',
                     age: 30
                      }, {
                     name: 'Reena Singh',
                     age: 25
                     }];
for(var i=0;i< $scope.userDetails.length;i++)
{
     console.log("This is age"+$scope.userDetails[i].age);
}
};

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
  <button ng-click="getAge()">Get age</button>
</div>

答案 1 :(得分:0)

我认为您正在寻找所有年龄段的人。请查看下面的代码。

var MyAppp = angular.module('MyAppp',[])
MyAppp.controller('ageController',function($scope){
$scope.getAge = function()
{
    $scope.userDetails = [{
                     name: 'Anil Singh',
                     age: 30
                      }, {
                     name: 'Reena Singh',
                     age: 25
                     }];
   var ages= $scope.userDetails.map(function(o){return o.age});
   console.log(ages)
   return ages;
};

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="MyAppp" ng-controller="ageController">
  <button ng-click="getAge()">Get age</button>
</div>