用于高级图表表示的格式数据

问题描述 投票:-1回答:1

我具有以下格式的数据。我想绘制一个折线图,以比较2017年和2018年所有月份的数据。

const listItems = [{
    "id": 1,
    "total": 21.15,
    "dat": "2017-10-21T08:32:36.000Z"
  },
  {
    "id": 2,
    "total": 22,
    "dat": "2017-11-24T13:46:16.000Z"
  },{
    "id": 3,
    "total": 11,
    "dat": "2017-11-24T13:46:16.000Z"
  },
  {
    "id": 4,
    "total": 12,
    "dat": "2018-04-02T09:15:35.000Z",
  }
]

我想以以下格式表示折线图:

var xAxis = {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ]
};
var series = [{
        name: '2017',
        data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,
            26.5, 23.3, 18.3, 13.9, 9.6
        ]
    },
    {
        name: '2018',
        data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8,
            24.1, 20.1, 14.1, 8.6, 2.5
        ]
    }
];

基本上,数据代表所有月份的总和。

node.js typescript highcharts
1个回答
0
投票

首先,编写一个从日期开始挖掘月份的函数,例如:

var dateToMonth = (date) => {
    var matched = /[\d]{4}-([\d]{2})-[.]*/g.exec(date)[1];
    return matched;
};

也写别人的采矿年。甚至是in_array函数:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

然后您必须编写一个函数来迭代您的数据并汇总相同月份的数据总和:

var format = (data) => {
    var month_format = [0,0,0,0,0,0,0,0,0,0,0,0];
    var last_format = [];
    data.map(e => {
        var year = dateToYear(e.date);
        var years = last_format.map(data_e => data_e.name);
        if (!inArray(year, years)) last_format.add({name: year, data: month_format});
        var month = dateToMonth(e.date);
        last_format.forEach(i => {
           if (i.name === year) i[month - a] += e.data;
        });
    });
    return last_format;
};
© www.soinside.com 2019 - 2024. All rights reserved.