转换JavaScript 2D数组

时间:2019-02-07 18:54:32

标签: javascript arrays django google-visualization

我正在创建一个仪表板以显示各种统计数据。我正在使用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进行转换。

我需要采取哪种方法的帮助。

2 个答案:

答案 0 :(得分:2)

您可以按日期对它们进行分组,然后使用Object.entries循环浏览分组的结果并将其转换为[date, "VHR", "VNA", "PAP"]

const 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]
];

const grouped = data.reduce((all, [key, date, value]) => {

  all[date] = {
    ...all[date],
    [key]: value
  };

  return all;
}, {});

const result = ["date", "VHR", "VNA", "PAP"].concat(
  Object.entries(grouped).map(([date, obj]) => [date, ...Object.values(obj)])
);

console.log(result);

答案 1 :(得分:2)

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

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; }