将数据从Json过滤到可以在HighChartsJs中使用的新数组



我目前正在使用HighCharts JS。对于要在HighCharts中显示的数据,我必须拥有如下最终数据:

[
{
name: 'Performing',
data: [1941404, 1028717, 697370, 0, 0, 0]
},
{
name: 'Non performing',
data: [0, 0, 0, 1759908, 890857, 280235]
},
{
name: 'Substandard',
data: [0, 0, 863825, 0, 0, 0]
},
{
name: 'Written-off',
data: [0, 0, 0, 0, 0, 77146]
}
]

"数据"是一个由 6 个对象组成的数组,填充图表的 xAxis。

但是,我有以下数据是通过MongoDb提供的

const chartData = [
{
"_id": {
"data": "90 - 180",
"status": "Non Performing"
},
"value": 1759908
},
{
"_id": {
"data": "360",
"status": "Written-off"
},
"value": 77146
},
{
"_id": {
"data": "360",
"status": "Non Performing"
},
"value": 280235
},
{
"_id": {
"data": "30 - 90",
"status": "Substandard"
},
"value": 863825
},
{
"_id": {
"data": "30 - 90",
"status": "Performing"
},
"value": 697370
},
{
"_id": {
"data": "180 - 360",
"status": "Non Performing"
},
"value": 890857
},
{
"_id": {
"data": "0 - 30",
"status": "Performing"
},
"value": 1028717
},
{
"_id": {
"data": "0",
"status": "Performing"
},
"value": 1941404
}
]

我需要过滤后一个代码,使其最终像前一个代码一样。非常重要的是,在数据数组中,我们最终得到 6 个对象,以确保我们填充整个 xAxis of Highcharts,因此我们看到很多零,其中没有提供数据。

我真的希望这能解决问题。感谢所有获得帮助的人。我很抱歉在偏移中如此模糊。

快速说明 数据数组的顺序如下:

0、0-30、30-90、90-180、180-360、360已编辑

所以这是我目前使用的代码:

const data = this.chartData
let series
series = Object.values(data.reduce((acc, currVal) => {
acc[currVal._id.status] = acc[currVal._id.status] || { 
name: currVal._id.status, 
data: [] 
};
acc[currVal._id.status].data.push(currVal.totalBookValue) //push the year to data array after converting the same to a Number
return acc //return the accumulator
}, {}))

这种工作,但它没有用 6 个元素填充 Data 数组。

您的问题可以通过一些遍历来解决,使用reduce()到达objectformmap()返回到arrayform(假设您发布的0360列表已完成)。

有关实际示例,请参见下文。

// Input.
const input = [
{
"_id": {
"data": "90 - 180",
"status": "Non Performing"
},
"value": 1759908
},
{
"_id": {
"data": "360",
"status": "Written-off"
},
"value": 77146
},
{
"_id": {
"data": "360",
"status": "Non Performing"
},
"value": 280235
},
{
"_id": {
"data": "30 - 90",
"status": "Substandard"
},
"value": 863825
},
{
"_id": {
"data": "30 - 90",
"status": "Performing"
},
"value": 697370
},
{
"_id": {
"data": "180 - 360",
"status": "Non Performing"
},
"value": 890857
},
{
"_id": {
"data": "0 - 30",
"status": "Performing"
},
"value": 1028717
},
{
"_id": {
"data": "0",
"status": "Performing"
},
"value": 1941404
}
]
// Depth.
const depth = ['0', '0 - 30', '30 - 90', '90 - 180', '180 - 360', '360']
// Object Form.
const objectform = input.reduce((accumulator, x) => {
const { _id, value } = x // _id. Value.
let { data, status } = _id // Status.
status = status.toLowerCase() // Lower Case.
const point = {...accumulator[status], [data]: value} // Data.
return {...accumulator, [status]: point} // Update + Return Accumulator.
}, {})
// Output.
const output = Object.keys(objectform).map((key) => {
return {
name: key, // Name.
data: depth.map((frame) => objectform[key][frame] || 0) // Data.
}
})
// Log.
console.log(output)

最新更新