I am currently facing an issue with my Vue component and template where I display employees along with their hours/scans by date. The problem is that the current mapping aggregates all hours and scans based on the first record's date.
The challenge arises because my table headers represent dates (today, tomorrow, and the day after). Therefore, I need to implement a v-if
statement for each header to compare it to the corresponding record's date. This means that for employee A123, there should only be one record, whereas for employee D432, there should be two records due to different dates.
How can I incorporate the date factor into the mapping process?
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: "#app",
data: {
rows: [{
employee: "A123",
hours: "15",
date: "2021-08-31",
scans: "4"
},
{
employee: "A123",
hours: "25",
date: "2021-08-31",
scans: "4"
},
{
employee: "D432",
hours: "82",
date: "2021-09-02",
scans: "2"
},
{
employee: "D432",
hours: "40",
date: "2021-09-01",
scans: "5"
}
]
},
methods: {
groupByField(list, field) {
const result = {};
list.forEach(item => {
const value = item[field];
if (value) {
if (!result[value]) {
result[value] = [];
}
result[value].push(item);
}
});
return result;
}
},
computed: {
compRows() {
const a = this.groupByField(this.rows, 'employee');
let b = Object.values(a)
return b.map(item => {
return {
employee: item[0].employee,
hours: item.reduce((acc, _item) => (+acc) + (+_item.hours), 0),
scans: item.reduce((acc, _item) => (+acc) + (+_item.scans), 0),
date: item[0].date
}
})
}
}
});
th,td{
padding:8px
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app" class="container">
<table class="table">
<thead>
<tr>
<th>Employee</th>
<th>hours</th>
<th>scans</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in compRows">
<td>{{row.employee}}</td>
<td>{{row.hours}}</td>
<td>{{row.scans}}</td>
<td>{{row.date}}</td>
</tr>
</tbody>
</table>
</div>