2017-05-08 62 views
0

我想基於範圍變量來格式化融合圖表的數據。 我有一個函數可以獲取分配給這個日期的日期和股票值。 所以我有2列:將數組中的元素添加到對象中,以格式化fusionchart數據

dates = [2017-04-28, 2017-04-27, 2017-04-26, 2017-04-25] 
stockValues = [150.25, 147.7, 146.56, 146.49] 

我想要做的是創建一個新的對象,看起來像這樣:

data: [{ 
    "label": "2017-04-28", 
    "value": "150.25" 
    }, 
    { 
    "label": "2017-04-27", 
    "value": "147.7" 
    }, 
    ... //and so on 
    ] 

我設法想出下面的代碼:

$scope.getStockData = function(stockID) { 
       $http.get('/stock', { 
        params : { 
         stockID : encodeURI(stockID) 
        } 
       }).then(function(response) { 
        $scope.stock = response.data; 
        var data={}; 
        $scope.data={}; 
        angular.forEach(response.data.dates,function(value){ 
         data["label"] = value; 
        }) 
        angular.forEach(response.data.stockValues,function(value){ 
         data["value"] = value; 
        }) 

        $scope.data = data; 

       }, function(response) { 
        $scope.showError = true; 
       }).finally(function() { 
        }); 
      }; 

問題是,此解決方案創建的對象如下所示:

{"label":"2017-04-25","value":"146.49"} 

因此,它只需要數組中的最後一個值。 如何讓我的對象看起來像我想要的樣子?

回答

0

例子:

const dates = ['2017-04-28', '2017-04-27', '2017-04-26', '2017-04-25'] 
 
const stockValues = ['150.25', '147.7', '146.56', '146.49'] 
 

 
const r = dates.map((d, i) => Object.assign({ 
 
    label: d, 
 
    value: stockValues[i] 
 
})) 
 

 
console.log(JSON.stringify(r, null, 2))

+0

作品很有魅力,謝謝! –

0

試試這個,你必須初始化數組,並在合適的位置上推。

$scope.getStockData = function(stockID) { 
    $http.get('/stock', { 
     params : { 
      stockID : encodeURI(stockID) 
     } 
    }).then(function(response) { 
     $scope.stock = response.data; 
     var data=[]; 
     $scope.data=[]; 
     angular.forEach(response.data.dates,function(value, i){ 
      data[i]["label"] = value; 
     }) 
     angular.forEach(response.data.stockValues,function(value, i){ 
      data[i]["value"] = value; 
     }) 

     $scope.data = data; 

    }, function(response) { 
     $scope.showError = true; 
    }).finally(function() { 
     }); 
}; 
相關問題