编程语言
首页 > 编程语言> > 转换JavaScript 2D数组

转换JavaScript 2D数组

作者:互联网

我正在创建一个仪表板,以显示各种统计数据.我正在使用Django和Google Charts创建图形.到目前为止,情况还不错,但我只遇到一种情况.

模型类是-

class Registration(models.Model):
    event_type = models.CharField(max_length=80)
    date_time = models.DateField()
    count = models.IntegerField()

我的查询是-

Registration.objects.filter(event_type__in=['VHRAssmntCompleted', 
    'VNAAssmntCompleted', 
    'NonsmokersDeclrtn',
    'MWBAssmntCompleted',
    'VHCAssmntCompleted',
    'SV Document Uploads',
    'PapSmear',
    'Mammogram',], 
    date_time__range=(d3,d1)).order_by('date_time')

我得到以下格式的数据:

[["VHR", "2019-02-1", 23],
["VNA", "2019-02-1", 34],
["PAP", "2019-02-1", 50],
["VHR", "2019-02-2", 92],
["VNA", "2019-02-2", 13],
["PAP", "2019-02-2", 65],
["VHR", "2019-02-3", 192],
["VNA", "2019-02-3", 43],
["PAP", "2019-02-3", 11]]

要创建需要以下格式的数据的Combo Chart(类似于python数据框):

[["date", "VHR", "VNA", "PAP" ],
["2019-02-1", 23,34,50],
["2019-02-2", 92,13,65],
["2019-02-3", 192,43,11]]

我无法找到一种方法,无法使用Django ORM查询本身对其进行格式化或使用JS进行转换.

我需要哪种方法的帮助.

解决方法:

您可以使用一个对象作为值的列位置,然后按日期和列收集数据.

var data = [["VHR", "2019-02-1", 23], ["VNA", "2019-02-1", 34], ["PAP", "2019-02-1", 50], ["VHR", "2019-02-2", 92], ["VNA", "2019-02-2", 13], ["PAP", "2019-02-2", 65], ["VHR", "2019-02-3", 192], ["VNA", "2019-02-3", 43], ["PAP", "2019-02-3", 11]],
    cols = { VHR: 1, VNA: 2, PAP: 3 },
    result = data.reduce((r, [key, date, value]) => {
        var row = r.find(([d]) => d === date);
        if (!row) {
            r.push(row = [date, 0, 0, 0]);
        }
        row[cols[key]] = value;
        return r;    
    }, [["date", "VHR", "VNA", "PAP"]]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

标签:google-visualization,arrays,javascript,django
来源: https://codeday.me/bug/20191024/1923287.html