I have an HTML table like this:
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Nouveaux FDES</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows">
<td> {{ row.details.id_inies }} </td>
<td> <a :href="row.url" target="_blank" rel="noreferrer noopener">{{ row.name }}</a></td>
<td style="text-align: center; vertical-align: middle;"> <input v-model="row.isSelected" type="checkbox"> </td>
</tr>
</tbody>
My goal is to get value in cells of the column ID and only the ones which are selected by user using the checkbox
I try something like this but it doesn't work:
{
const selectedFDES = this.rowsScraped.filter((fdes) => fdes.isSelected === true);
const idList = selectedFDES.reduce((acc, item) => {
acc[item.details.id_inies] = [];
return acc;
}, []);
console.log(idList);
this.$http.admin.putScrapedFDES(idList);
}
Your reducer function doesn't make much sense. It should probably look like this:
const selectedFDES = this.rowsScraped.filter(r => r.isSelected);
const idList = selectedFDES.reduce((acc, item) => {
acc.push(item.details.id_inies);
return acc;
}, []);
console.log(idList);
this.$http.admin.putScrapedFDES(idList);
For your case, I believe a .map() would be shorter, cleaner and more readable:
const idList = this.rowsScraped
.filter(r => r.isSelected)
.map(r => r.details.id_inies);
this.$http.admin.putScrapedFDES(idList);
See it working here:
new Vue({
el: '#app',
data: () => ({
rows: ['First', 'Second', 'Third']
.map((name, i) => ({
name: `${name} row`,
details: {
id_inies: i + 1,
},
url: '#',
isSelected: false
}))
}),
computed: {
selectedRows() {
return this.rows
.filter(row => row.isSelected)
.map(row => row.details.id_inies)
}
},
watch: {
selectedRows(newVal, oldVal) {
// This runs every time selectedRows changes value
console.log({ newVal, oldVal });
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<div id="app">
<table>
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Nouveaux FDES</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows">
<td> {{ row.details.id_inies }} </td>
<td> <a :href="row.url" target="_blank" rel="noreferrer noopener">{{ row.name }}</a></td>
<td style="text-align: center; vertical-align: middle;"> <input v-model="row.isSelected" type="checkbox"> </td>
</tr>
</tbody>
</table>
<pre v-text="selectedRows" />
</div>