Bi-dimensionnal table with dynamic v-bind
by RomainMazB
HTML
<div id="app">
<table class="table w-full">
<thead>
<tr>
<th></th>
<th v-for="(day, index) in daysArray">
{{ day }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(time, timeIndex) in timesArray" :key="timeIndex">
<td>{{ timeIndex }}</td>
<td v-for="(day, dayIndex) in time">
<input type="checkbox" v-bind:id='`{ "`+timeIndex+`": "`+day+`" }`' :value='`{ "`+timeIndex+`": "`+day+`" }`' v-model="selectedTimesArray">
</td>
</tr>
</tbody>
</table>
<button @click="mergeToJSON()">Merge data to store it</button>
</div>
CSS
.wrapper {
max-width: 350px;
}
.flex {
display: flex;
justify-content: space-between;
}
.child {
display: none;
}
.showChild {
display: block
}
JavaScript
new Vue({
el: '#app',
data: {
daysArray: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
timesArray: {
'10:00 - 10:30': ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'],
'10:30 - 11:00': ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
},
selectedTimesArray: []
},
methods: {
mergeToJSON() {
let result = {};
this.selectedTimesArray.forEach((val) => {
let valAsObject = JSON.parse(val); // Get object
for (let [key, value] of Object.entries(valAsObject)) {
if(!result.hasOwnProperty(key)) result[key] = []; // First iteration of this key, creating the array
result[key].push(value); // Push value in the array
}
});
console.log(result);
}
},
watch: {
selectedTimesArray() {
console.table(this.selectedTimesArray);
}
}
})