我正在尝试在角度js中实现图表表示。
http://jtblin.github.io/angular-chart.js/
我能够实现简单的图表,但我有一个下面的数据来表示。它是JSON格式。我需要有关如何将JSON转换为数组以表示为图表的帮助。以下是JSON
[{"value": {"DE":2,"NP":20,"BD":28,"TW":1},
"end_time":"2016-07-05T07:00:00+0000"},
{"value":{"DE":5,"NP":11,"BD":22,"BE":2,"FJ":2},
"end_time":"2016-07-06T07:00:00+0000"},
{"value":{"DE":5,"NP":24,"BD":29},
"end_time":"2016-07-07T07:00:00+0000"}]
我正在尝试将其转换为格式
$scope.labels = ["January", "February", "March", "April", "May", "June","July"];
$scope.series = ['Series A', 'Series B'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
我知道我需要迭代我的JSON对象并创建数组。
我的问题是我在每个JSON对象中都有不同的标签。如何转换它创建一个数组,其中包含每个值中的所有标签,并仍然保持计数的顺序。如下所示
$scope.labels = ["DE", "NP", "BD", "TW", "BE", "FJ"];
$scope.series = ["2016-07-05T07:00:00+0000","2016-07-06T07:00:00+0000","2016-07-07T07:00:00+0000"]
$scope.data = [ [2,20,28,1,0,0],
[5,11,22,0,2,2],
[5,24,29]
]
如果使用angularjs中的不同库或图表可以更好地实现这一点,请建议
答案 0 :(得分:2)
你有没有尝试过什么?你没有显示任何解决方案。无论如何,这是一个可能的实现
var source = [
{"value": {"DE":2,"NP":20,"BD":28,"TW":1},
"end_time":"2016-07-05T07:00:00+0000"},
{"value":{"DE":5,"NP":11,"BD":22,"BE":2,"FJ":2},
"end_time":"2016-07-06T07:00:00+0000"},
{"value":{"DE":5,"NP":24,"BD":29},
"end_time":"2016-07-07T07:00:00+0000"}
]
var $scope = {};
$scope.labels = [];
$scope.data = [];
$scope.series = [];
source.forEach(function(item){
$scope.series.push(item.end_time)
var values = []
Object.keys(item.value).forEach(function(key) {
if ($scope.labels.indexOf(key) === -1) {
$scope.labels.push(key)
}
values.push(item.value[key])
})
$scope.data.push(values)
})
console.log($scope)