如何使用JavaScript格式化Highcharts的MongoDB样式表数据?

时间:2016-02-20 10:45:49

标签: javascript json mongodb charts highcharts

我有一些类似的数据:

[{
    "displayname": "Someone",
    "artistname": "Artist",
    "songtitle": "Title",
    "difficultyid": 5,
    "scoreactual": 642.5,
    "scorepossible": 658.5,
    "id": 26324,
    "timeachieved": 1455948669
}, {
    "displayname": "Someone",
    "artistname": "Another Artist",
    "songtitle": "Another Song",
    "difficultyid": 5,
    "scoreactual": 547.5,
    "scorepossible": 574.5,
    "id": 26324,
    "timeachieved": 1455948669
}, {
    "displayname": "SomeoneElse",
    "artistname": "Another Artist",
    "songtitle": "Another Song",
    "difficultyid": 6,
    "scoreactual": 544,
    "scorepossible": 574.5,
    "id": 26323,
    "timeachieved": 1455948526
}]

当我使用DataGrid时,我记得能够使用一些回调和对象属性来格式化每个JSON对象;虽然在使用Highcharts时,我发现我必须做很多复杂的数据操作才能将这些数据变成Highcharts可用的东西。

最终的数据结构将是这样的:

{
    categoryData: ['Title', 'Another Song']
    seriesData: [{
        name: 'Someone'
        data: [642.5, 547.5]
    }, {
        name: 'SomeoneElse'
        data: [0, 544]
    }]
}

以下是我编写的代码,通常用于任何3个数据选择器的转换(我相信这段代码太复杂了):

export function getSeriesDataFromTableRows(selectors) {
    const { tableRows, nameSelector, categorySelector, dataSelector, cb } = selectors

    let nameSelections = {},
        categorySelections = {},
        categoryCount = 0,
        seriesData = [],
        categoryData = []

    for (let tableRow of tableRows) {
        let name = tableRow[nameSelector],
            category = tableRow[categorySelector]

        !nameSelections[name]
            && (nameSelections[name] = [])
        nameSelections[name].push(tableRow)

        !categorySelections[category] && (categorySelections[category] = categoryCount++)
    }

    for (let category of Object.keys(categorySelections)) {
        let categoryIndex = categorySelections[category]
        categoryData[categoryIndex] = category
    }

    for (let name of Object.keys(nameSelections)) {
        let tableRowSelections = nameSelections[name],
            data = []

        for (let tableRow of tableRowSelections) {
            let category = tableRow[categorySelector],
                categoryIndex = categorySelections[category],
                dataSelection = tableRow[dataSelector]

            data[categoryIndex] = cb ? cb(dataSelection) : dataSelection
        }

        for (let categoryIndex = 0; categoryIndex < categoryCount; categoryIndex++) {
            !data[categoryIndex] && (data[categoryIndex] = 0)
        }

        seriesData.push({
            name,
            data
        })
    }

    return {
        seriesData,
        categoryData
    }
}

有没有更好的方法在JavaScript中为Highcharts格式化这些数据?或者我可以使用一种工具来为我做这个吗?

0 个答案:

没有答案