从对象数组中获取值angularjs,它只返回最后一项

时间:2018-01-01 22:42:09

标签: javascript angularjs

我想使用angular.forEach从对象数组中获取值 确切地说,每个项目中元素的每个值。当我使用angular.forEach函数并循环对象数组时,它只返回最后一项的值。我花了好几个小时去寻找解决方案,但却徒劳无功。

请查看我的代码:

这是json文件中的对象数组,我想从中获取值。

data.json:

table_2 (col_b, col_c)

controller.js:

[
  {
    "platform": "web-desktop",
    "cdn": 4.3673292887e+10,
    "p2p": 5.667683381e+09,
    "total": 4.9340976268e+10,
    "upload": 5.774321084e+09,
    "percentage": 12,
    "viewers": 1,
    "maxViewers": 10,
    "averageViewers": 1.5725853094274147,
    "trafficPercentage": 69.49888073943228,
    "live": "unknown"
  },
  {
    "platform": "android",
    "cdn": 1.7035777808e+10,
    "p2p": 1.526916976e+09,
    "total": 1.8562694784e+10,
    "upload": 2.753179184e+09,
    "percentage": 9,
    "viewers": 1,
    "maxViewers": 12,
    "averageViewers": 1.416065911431514,
    "trafficPercentage": 26.14635154335973,
    "live": "unknown"
  },
  {
    "platform": "ios",
    "cdn": 2.994960132e+09,
    "p2p": 9.6722616e+07,
    "total": 3.091682748e+09,
    "upload": 3.3788984e+07,
    "percentage": 4,
    "viewers": 1,
    "maxViewers": 3,
    "averageViewers": 1.152542372881356,
    "trafficPercentage": 4.354767717207995,
    "live": "unknown"
  }
]

结果如下:

'use strict';
var app= angular.module('app');
app.controller('MainController',['$scope', '$http', MainController]);

function MainController ($scope, $http) {

    var request = {
        method: 'get',
        url: 'data.json',
        dataType: 'json',
        contentType: "application/json"
    };

    $scope.arrData = new Array;    
    $http(request)
        .then(function onSuccess(jsonData) {

            // LOOP THROUGH DATA IN THE JSON FILE.
            angular.forEach(jsonData.data, function (item) {

                //Get data in each object
               $scope.arrData = Object.keys(item).map(function(key){return item[key]});// get all values

            });
            console.log($scope.arrData);
        });
}

或者,我希望得到所有这些项目。我应该在代码中添加什么才能使其正常工作!感谢。

1 个答案:

答案 0 :(得分:1)

您在id in set_a

的每次迭代中都会覆盖$scope.arrData

使用forEach代替map()并在外部地图()回调中返回您的键映射

forEach()