将数组中的元素添加到对象以格式化 fusionchart 数据

Add elements from array to object to format fusionchart data

我想根据范围变量格式化我的融合图表的数据。 我有一个函数可以获取分配给该日期的日期和股票价值。 所以我有 2 个数组:

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"}

所以它只需要数组中的最后一个值。 我怎样才能让我的对象看起来像我想要的那样?

示例:

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))

试试这个,你必须初始化一个数组,并在正确的位置推送。

$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() {
      });
};