我想让数组适合从SQL返回的Highchart数据。
此数组应该可供Highchart使用。
你能帮我解决这个问题吗?
从SQL返回json值:
{
"FuelConsumption": [{
"Unit": "Computing",
"UnitID": 9,
"DateofPurchase": "18.04.2016",
"Liter": 2
}, {
"Unit": "Transportation",
"UnitID": 10,
"DateofPurchase": "18.04.2016",
"Liter": 3453
}, {
"Unit": "GeneralManager",
"UnitID": 7,
"DateofPurchase": "20.04.2016",
"Liter": 5
}, {
"Unit": "Boss",
"UnitID": 8,
"DateofPurchase": "20.04.2016",
"Liter": 4564
}, {
"Unit": "Computing",
"UnitID": 9,
"DateofPurchase": "20.04.2016",
"Liter": 579
}, {
"Unit": "Transportation",
"UnitID": 10,
"DateofPurchase": "20.04.2016",
"Liter": 337
}, {
"Unit": "Boss",
"UnitID": 8,
"DateofPurchase": "21.04.2016",
"Liter": 3
}, {
"Unit": "Transportation",
"UnitID": 10,
"DateofPurchase": "21.04.2016",
"Liter": 22
}]
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
我希望以这种方式获得结果:
{
name: 'Transportation',
data: [3453, 337, 22]
}, {
name: 'Computing',
data: [2, 5, 579]
}, {
name: 'Boss',
data: [4564, 3]
}
答案 0 :(得分:1)
你可以从json创建一个哈希, &#39;单位&#39;值为关键字,这是一个数组,并继续添加&lt; Liter&#39;该数组的值。完成后,从该哈希创建json。
var hash = {};
data.FuelConsumption.forEach(function(obj) {
if (!hash[obj.Unit]) {
hash[obj.Unit] = [];
}
hash[obj.Unit].push(obj.Liter);
});
var newData = [];
for (var key in hash) {
newData.push({
name: key,
data: hash[key]
});
}
如果您使用的是Lodash,那么
var newData2 = _.chain(data.FuelConsumption)
.groupBy('Unit')
.map(function(obj) {
return {
name: _.uniq(_.pluck(obj, 'Unit'))[0],
data: _.uniq(_.pluck(obj, 'Liter'))
};
})
.value();
答案 1 :(得分:0)
如果您可以使用下划线,答案如下:
_.chain(data["FuelConsumption"])
.groupBy('Unit')
.mapObject((val, key)=>({name:key, data:val.map(x => x.Liter)}))
.value()
如果您使用任何其他JavaScript库,它就会相似。