制表符设置帮助,使用URL中的JSON数据

时间:2019-01-27 22:20:02

标签: javascript json tabulator

我正在尝试通过从URL(以.json结尾)导入JSON数据来建立Tabulator表。当前访问URL时,我得到以下数据:

{"27-Jan-2019-2205":{"question1a":0,"question1b":2,"question1c":1,"question2":3,"question3":1,"question4":3,"question5":0,"question6":1,"question7":4,"question8a":1,"question8b":2,"question8c":1},"27-Jan-2019-2206":{"question1a":2,"question1b":0,"question1c":2,"question2":2,"question3":1,"question4":3,"question5":1,"question6":3,"question7":2,"question8a":0,"question8b":2,"question8c":1}}

美化了,这是:

{  
   "27-Jan-2019-2205":{  
      "question1a":0,
      "question1b":2,
      "question1c":1,
      "question2":3,
      "question3":1,
      "question4":3,
      "question5":0,
      "question6":1,
      "question7":4,
      "question8a":1,
      "question8b":2,
      "question8c":1
   },
   "27-Jan-2019-2206":{  
      "question1a":2,
      "question1b":0,
      "question1c":2,
      "question2":2,
      "question3":1,
      "question4":3,
      "question5":1,
      "question6":3,
      "question7":2,
      "question8a":0,
      "question8b":2,
      "question8c":1
   }
}

我理想的表格设置是将日期作为列标题,然后(如果可能)在第一行中包含问题。随时间推移,JSON数据将添加到其他日期/相应的答案集中。

可以在此处看到一个粗略的Excel样机:

Excel table mockup

我目前正在使用jQuery的getJSON函数导入数据,如下所示:

$.getJSON(url, function(data) {
// Table setup
table.setData(data);
}

我该如何实现?

1 个答案:

答案 0 :(得分:3)

为您提供一些数据转换。这绝对不是性能最高的方法,但应该是最简单的方法。

首先,提取所需的列:

const columns = Object.keys(data)

然后我们要获取所有行:

let rows = []
for (column of columns) {
    rows = Object.keys(data[column]).reduce((a, b) => {
        if (!a.includes(b)) a.push(b)
        return a
    }, rows)
}

然后我们想将它们结合起来

rows.map(row => {
    let rowData = {Question: row}
    for (column of columns) {
        rowData[column] = data[column][row]
    }
    return rowData
})

这是全部放在一起:

const data = {"27-Jan-2019-2205":{"question1a":0,"question1b":2,"question1c":1,"question2":3,"question3":1,"question4":3,"question5":0,"question6":1,"question7":4,"question8a":1,"question8b":2,"question8c":1},"27-Jan-2019-2206":{"question1a":2,"question1b":0,"question1c":2,"question2":2,"question3":1,"question4":3,"question5":1,"question6":3,"question7":2,"question8a":0,"question8b":2,"question8c":1}}

//Get the columns
let columns = Object.keys(data)

//Get unique questions
let rows = []
for (column of columns) {
  rows = Object.keys(data[column]).reduce((a, b) => {
    if (!a.includes(b)) a.push(b)
    return a
  }, rows)
}

//Extract row data
rows = rows.map(row => {
  let rowData = {Question: row}
  for (column of columns) {
    rowData[column] = data[column][row] || "No Data"
  }
  return rowData
})

//Add the 'Question' column
columns.unshift("Question")

//Log the results
console.log(columns.map(c => ({title: c, field:c})))
console.log(rows)