I am working on ReactJS and was wondering if there is a way to convert a javascript array from row into column.
[
{ 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' }
]
I want to convert this into data an html table/div like this:
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
I found this excellent library - json-to-pivot-json. This is something that I wanted to use, but only issue is that aggregates the value.
I see lot of examples in sql but couldn't find anything similar for javascript.
To help others, I am adding the complete JSX code to display the result as suggested by 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>