我正在绘制一个图表,为此我想转换下面的 json
var jsonArray = [{
"tagValueName": "PCI",
"tagValueId": 1,
"priorityAlertsCount": 20,
"investigationAlertsCount": 140,
"incidentAlertsCount": 100,
"otherAlertsCount": 40
}, {
"tagValueName": "ABC",
"tagValueId": 2,
"priorityAlertsCount": 100,
"investigationAlertsCount": 60,
"incidentAlertsCount": 20,
"otherAlertsCount": 20
}];
但图表需要以下格式的数据
var jsonData = [{
"tagValueName" : "PCI",
"type": "priorityAlertsCount",
"count": "20",
},
{
"tagValueName" : "PCI",
"type": "investigationAlertsCount",
"count": "140",
},
{
"tagValueName" : "PCI",
"type": "incidentAlertsCount",
"count": "100",
},
{
"tagValueName" : "PCI",
"type": "otherAlertsCount",
"count": "40",
},{
"tagValueName" : "ABC",
"type": "priorityAlertsCount",
"count": "100",
},{
"tagValueName" : "ABC",
"type": "investigationAlertsCount",
"count": "60",
}];
如何将 JSON 从我的格式转换为图表所需的格式?
请帮助我,因为我是 JS 新手?
我想绘制一个类似 this 的图表.
最佳答案
看看this jsbin .
var jsonArray = [{
"tagValueName": "PCI",
"tagValueId": 1,
"priorityAlertsCount": 20,
"investigationAlertsCount": 140,
"incidentAlertsCount": 100,
"otherAlertsCount": 40
}, {
"tagValueName": "ABC",
"tagValueId": 2,
"priorityAlertsCount": 100,
"investigationAlertsCount": 60,
"incidentAlertsCount": 20,
"otherAlertsCount": 20
}];
var descriptionProperties = ['tagValueName', 'tagValueId'];
var nameProperty = ['tagValueName'];
function formatData(dataArray) {
return dataArray.reduce(function(acc, item) {
var formattedItems = Object.keys(item)
.filter(function(key) {
return descriptionProperties.indexOf(key) === -1;
})
.map(function(key) {
var obj = {};
var value = item[key];
obj.type = key;
obj.count = value;
obj[nameProperty] = item[nameProperty];
return obj;
});
acc = acc.concat(formattedItems);
return acc;
}, []);
}
console.log(formatData(jsonArray));
基本上你应该看看基本的数组函数,例如 concat
以及高阶函数 map
, filter
和 reduce
我用它来按照您需要的方式转换数据。
关于javascript - 将 Json 格式转换为圆形装箱图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40968100/