0

I want to format the data of my fusion chart based on scope variable. I have a function which gets dates and stock values assigned to this dates. So I have 2 arrays:

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

What I want to do is to create a new object which looks like this:

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

I managed to come up with following code:

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

The problem is that this solution creates object which looks like this:

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

So it takes only the last values from array. How can I make my object look the way I want it to?

2 Answers 2

1

Example:

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this, you must initialize an array, and the push at the right location.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.