[英]Javascript: how can I improve these map functions?
I have a similar structure:我有一个类似的结构:
const items = [
{
hip: 40,
waist: 41,
neck: 42,
knee: 43,
arm: 44,
weight: 45,
},
{
hip: 46,
waist: 47,
neck: 48,
knee: 49,
arm: 50,
weight: 51,
}
];
To use it in Highcharts, I need to transform in a similar:要在 Highcharts 中使用它,我需要进行类似的转换:
series: [{
name: 'Installation',
data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
}, {
name: 'Manufacturing',
data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
}, {
name: 'Sales & Distribution',
data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
}, {
name: 'Project Development',
data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
}, {
name: 'Other',
data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
}],
So, I wrote this:所以,我写了这个:
const singleItem = props.items[0];
const keys = Object.keys(singleItem);
let singleSerie = [];
keys.map(key => {
let tempData = {
name: key,
data: []
};
const series = props.items.map(el => {
return el[key]
});
tempData.data = series
singleSerie.push(tempData)
return singleSerie;
})
It works, but it seems... "ugly".它有效,但似乎......“丑陋”。 Is it possible to improve it?
有没有可能改进它?
You can simplify to你可以简化为
const keys = Object.keys(props.items[0]);
const singleSeries = keys.map(key => {
return {
name: key,
data: props.items.map(el => el[key]),
};
});
When already using map
, don't use push
.当已经使用
map
,不要使用push
。 And you can just inline the series
expression in the data object literal.你可以只内联
series
数据表达对象字面值。
Also you might want to hardcode the keys
, so that you don't get back no series if the items
array is empty.此外,您可能想要对
keys
进行硬编码,这样如果items
数组为空,您就不会返回 no series 。
You can map the keys to their data points.您可以将键映射到它们的数据点。
const items = [ { hip: 40, waist: 41, neck: 42, knee: 43, arm: 44, weight: 45 }, { hip: 46, waist: 47, neck: 48, knee: 49, arm: 50, weight: 51 } ]; const toSeries = (data) => Object.keys(data?.[0]).map((name) => ({ name, data: data.map(obj => obj[name]) })); const chart = Highcharts.chart('container', { chart: { type: 'line' }, title: { text: 'Title' }, xAxis: { title: { text: 'X-Axis Label' } }, yAxis: { title: { text: 'Y-Axis Label' } }, series: toSeries(items) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/9.3.0/highcharts.min.js"></script> <div id="container"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.