如何将JSON对象合并在一起

时间:2016-11-08 10:43:54

标签: angularjs json

我想制作一个条形图,我有两个函数,每个函数都返回数据例如: 第一个函数1,:

$scope.data = {
    labels: ['Jan', 'Feb', 'Mar'],
    datasets: [
        {
            label: 'My First dataset',
            fillColor: 'rgba(220,220,220,0.2)',
            strokeColor: 'rgba(220,220,220,1)',
            pointColor: 'rgba(220,220,220,1)',
            pointStrokeColor: '#fff',
            pointHighlightFill: '#fff',
            pointHighlightStroke: 'rgba(220,220,220,1)',
            data: [55, 40, 84]
        }
    ]
};

返回第二个函数:

$scope.data = {
    labels: ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [

        {
            label: 'My Second dataset',
            fillColor: 'rgba(151,187,205,0.2)',
            strokeColor: 'rgba(151,187,205,1)',
            pointColor: 'rgba(151,187,205,1)',
            pointStrokeColor: '#fff',
            pointHighlightFill: '#fff',
            pointHighlightStroke: 'rgba(151,187,205,1)',
            data: [28, 48, 40, 19, 86, 27, 90, 102, 123]
        }
    ]
};

我的问题是如何将这个结果合并到最终结果中:

 $scope.data = {
    labels: ['Jan', 'Feb', 'Mar','Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [
      {
            label: 'My Second dataset',
            fillColor: 'rgba(151,187,205,0.2)',
            strokeColor: 'rgba(151,187,205,1)',
            pointColor: 'rgba(151,187,205,1)',
            pointStrokeColor: '#fff',
            pointHighlightFill: '#fff',
            pointHighlightStroke: 'rgba(151,187,205,1)',
            data: [28, 48, 40, 19, 86, 27, 90, 102, 123]
        },
        {
            label: 'My Second dataset',
            fillColor: 'rgba(151,187,205,0.2)',
            strokeColor: 'rgba(151,187,205,1)',
            pointColor: 'rgba(151,187,205,1)',
            pointStrokeColor: '#fff',
            pointHighlightFill: '#fff',
            pointHighlightStroke: 'rgba(151,187,205,1)',
            data: [28, 48, 40, 19, 86, 27, 90, 102, 123]
        }
    ]
};

3 个答案:

答案 0 :(得分:1)

您可以轻松地执行以下操作:

$scope.data.labels = $scope.data1.labels.concat($scope.data2.labels);
$scope.data.datasets = $scope.data1.datasets.concat($scope.data2.datasets);

在您的情况下可能(假设您没有包含这些功能):

$scope.data = { labels: [], datasets: [] };

getFirstDataSet(function(response) {
    concatToData(response);
});

getSecondDataSet(function(response) {
    concatToData(response);
});

function concatToData(response) {
    $scope.data.labels = $scope.data.labels.concat(response.labels);
    $scope.data.datasets = $scope.data.datasets.concat(response.datasets);
}

答案 1 :(得分:1)

使用concat方法。

 var finalObj = data1.concat(data2);

答案 2 :(得分:0)

你可以做;

$scope.data1.datasets.push($scope.data2.datasets[0]);

我建议不要为了单独的函数绑定到同一个数组。