我该怎么做:
var colors = ["#1f77b4", "#ff7f0e","#2ca02c", "#d62728"];
file =
[
{
DeviceName: 'DeviceName1',
counter1: '85%',
counter2: '87%',
counter3: '75%',
counter4: '63%' },
{
DeviceName: 'DeviceName2',
counter1: '85%',
counter2: '87%',
counter3: '75%',
counter4: '63%'
}
]
到此:
data = [
{
key: "counter1",
color: "#1f77b4",
values:
[
{ x : "DeviceName1", y : '85%' },
{ x : "DeviceName2", y : '87%' }
]
},
{
key: "counter2",
color: "#ff7f0e",
values:
[
{ x : "DeviceName1", y : '85%' },
{ x : "DeviceName2", y : '87%' }
]
},
{
key: "counter3",
color: "#2ca02c",
values:
[
{ x : "DeviceName1", y : '85%' },
{ x : "DeviceName2", y : '87%' }
]
},
{
key: "counter4",
color: "#d62728",
values:
[
{ x : "DeviceName1", y : '85%' },
{ x : "DeviceName2", y : '87%' }
]
}
];
所以我基本上想在数组的每个对象中使用1个计数器
这是我开始的,还有很长的路要走,但我想知道如何或是否使用map或reduce来实现这一点。
file.map(function(item,i){
return { key: item
}
})
答案 0 :(得分:0)
这段代码非常随意,但是如果您想进行特定的转换,可以这样做:
https://jsfiddle.net/na2ysko2/
var data = [];
Object.keys(file[0])
.filter(function(k){ return k !== 'DeviceName' })
.forEach(function(key,i) {
data.push({
key: key,
color: colors[i],
values: file.map(function(d) {
return {
x: d.DeviceName,
y: d[key]
}
})
});
});
这使得很多假设数据始终采用您指定的格式。