2017-04-20 52 views
0

我正在使用ag-grid作为应用程序,它只需要数组来显示行。我有一个从API返回的对象。这个调用总是只返回1个对象。我想将对象转换成长度1. 的数组这是我的代码:将对象放入AngularJS中的数组中

jobResult.paged().$promise.then(function (results) { 
    //ag-grid needs the result to be in an array 
    var arrayResult = []; 
    angular.forEach(function(results){ 
     arrayResult.push(results); 
    }); 
    $scope.jobResult = arrayResult; 

    if ($scope.lastResultGridOptions.api) {       
     $scope.lastResultGridOptions.api.setRowData($scope.jobResult); 
          $scope.lastResultGridOptions.api.sizeColumnsToFit(); 
} 
..rest of function 

results对象具有从API的数据。但.foreach函数不会将对象推入数组中。 我错过了什么?

+0

你能告诉我们结果的模式吗? – zero298

+0

[documentation](https://docs.angularjs.org/api/ng/function/angular.forEach)对于如何使用'angular.forEach'非常清楚。也许是时候阅读了? –

+0

你想完成什么? –

回答

2

angular.foreach是错误的,

正确的方法是,然后你可以带钥匙或价值并推至阵列,

angular.forEach(results, function(value, key){ 
     //push key or value 
     arrayResult.push(value); 
    }); 
+0

我想要的数组的第一个元素是'results'。什么是价值和关键来自? –

+0

你有什么内部结果?它是一个数组还是一个对象? – Sajeetharan

+0

我想通了。我需要推动价值。这工作。感谢您的帮助,尽管基本问题。 –

0

你的解释,希望数组长度1结果为[0],为什么不只是将结果推送到数组中:

arrayResult.push(results) 

如果您尝试从结果中创建一个数组,然后你想要在结果上运行.forEach:

results.forEach(function(res) { arrayResult.push(res); })