我正在使用ReactJS,想知道是否有办法将JavaScript数组从行转换为列。
[
{ study: 'KOOS', date: '05/06/2005', question: 'Standing upright', answer: 'Moderate' },
{ study: 'KOOS', date: '05/06/2006', question: 'Standing upright', answer: 'Severe' },
{ study: 'KOOS', date: '05/06/2007', question: 'Standing upright', answer: 'Extreme' },
{ study: 'KOOS', date: '05/06/2008', question: 'Standing upright', answer: 'Severe' },
{ study: 'KOOS', date: '05/06/2005', question: 'Going up or down stairs', answer: 'Extreme' },
{ study: 'KOOS', date: '05/06/2006', question: 'Going up or down stairs', answer: 'Moderate' },
{ study: 'KOOS', date: '05/06/2007', question: 'Going up or down stairs', answer: 'Extreme' },
{ study: 'KOOS', date: '05/06/2008', question: 'Going up or down stairs', answer: 'Moderate' }
]
我想将这个转换成数据,然后放到一个 HTML 表格/div 中,就像这样:
Study: Koos
Question | 05/06/2005 | 05/06/2006 | 05/06/2007 | 05/06/2008
Standing upright | Moderate | Severe | Extreme | Severe
Going up or down stairs | Extreme | Moderate | Extreme | Moderate
我发现了这个很好的库 - json-to-pivot-json。这是我想要使用的东西,但唯一的问题是它汇总值。
我看到很多SQL的例子,但找不到任何类似于JavaScript的例子。
为了帮助其他人,我将添加完整的JSX代码以显示结果,如
Rafael
所建议的。var output = coll2tbl(surveyResult, "question", "date", "answer");
const mappedCells = output.cells.map((row, index) => {
row.unshift(output.row_headers[index]);
return row;
})
<table>
<thead>
<th>Question</th>
{
output.col_headers.map(c => {
return (
<th>{c}</th>
);
})
}
</thead>
<tbody>
{
mappedCells.map(row => (
<tr>{ row.map(cell => (<td>{cell}</td>))}</tr>
))
}
</tbody>
</table>