Convert Rows To Column From Javascript Array
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 uprig
Solution 1:
Collection to Table-Ready Data-Structure
Pass the collection and the appropriate property descriptors to the coll2tbl
function and it will output a table-ready data-structure:
var data = [
{ 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' }
];
functionget_prop(obj, prop) {
return prop.split('.').reduce((o,k) => obj[k], obj);
}
functioncoll2tbl(coll, row_header, col_header, cell) {
var table = {};
var row_headers = [];
var cols = {};
coll.forEach(a => {
var h = get_prop(a, row_header);
if (h intable === false) {
table[h] = {};
row_headers.push(h);
}
var c = get_prop(a, col_header);
cols[c] = null;
table[h][c] = get_prop(a, cell);
});
var cells = [];
for (var row intable)
cells.push(Object.values(table[row]));
return { row_headers, col_headers: Object.keys(cols), cells };
}
var table = coll2tbl(data, 'question', 'date', 'answer');
console.log(table);
Output:
{ row_headers: [ 'Standing upright', 'Going up or down stairs' ],
col_headers: [ '05/06/2005', '05/06/2006', '05/06/2007', '05/06/2008' ],
cells:
[ [ 'Moderate', 'Severe', 'Extreme', 'Severe' ],
[ 'Extreme', 'Moderate', 'Extreme', 'Moderate' ] ] }
Making the thead
- add a static
th
to the beginning of thethead
, this is where yourQuestion
string will go. - add a
th
per ch in col_headers
Making the tbody
- iterate the
cells
returned bycoll2tbl()
.- every parent iteration, make a new
tr
. - add the row header cell by using the parent iterator's counter to grab the corresponding row header (
table.row_headers[i]
). - The inner loop will create the cells,
td
, (table.cells[i][j]
).
- every parent iteration, make a new
Ideally, you would make a react component that takes this data-structure and creates the html for you.
Post a Comment for "Convert Rows To Column From Javascript Array"