calculate 2d array with reduce in vuejs - vue.js

In Vue, I'm inserting a value in a 2d array input field and calculating it per row, but the total value that is being returned only calculates the first row, and when I display, the computed value is all the same.
How can i calculate the inputted value so that the value will compute it per row and not just the first value?
This is what i get:
sample image of the value
FIDDLE:jsfiddle
NAME | VALUE1 | VALUE2 | TOTAL
name1 | 1 | 1 | 2
name2 | 2 | 3 | 2
name3 | | | 2
script
data() {
return {
form: new Form({
labStudentScores: [],
})
};
},
computed: {
studentTotalScore: function() {
return this.form.labStudentScores.reduce(
(acc, item) => acc + parseInt(item.value),
0
);
},
methods: {
addScore: function() {
this.form.labStudentScores.push({ value: [] });
}
}
Template
<button type="button" #click="addScore">score(+)</button>
//classlists is comming from http request
<tr v-for="(classlist,index) in classlists" :key="'lab'+ classlist.id">
<td>{{index +1}}</td>
<td>
{{classlist.student}}
</td>
<td v-for="(labStudentScore,i) in form.labStudentScores" :key="i">
<input v-model="labStudentScore.value[index]" />
</td>
<td>{{studentTotalScore}}</td>
</tr>

Your computed variable is really only one number studentTotalScore. Since you want a number for each row, this computed value should be an array studentTotalScores. Each row should have its own index.
this.form.labStudentScores[index].push(value);
And in your template you should also refer to the correct row too for calulation.
{{studentTotalScore[index]}}
Of course your compute function should also only compute values of the related row.

Related

Update column with the same value apart from an object removed in column in Sqlite

I want to remove an object from a json column in Sqlite and I can't make it work. The json column contains a nested object, has the following type:
{
a: number;
pair: {
field1: string;
field2: string;
}[]
}
I want to update the column "ArrayColumn" with the same values but remove the object that has field1 equal to "0" and field2 equal to "1" . Every row contains the "pair" array, but not all the "pair" arrays in ArrayColumn contain this value ({"field1":"0", "field2":"1"})
I have the following structure:
Id| ArrayColumn
--------------------------------------------------------------------------------------------
1 | { "a":1, "pair":[{"field1":"0", "field2":"1"},{"field1":"C", "field2":"D"},{"field1":"E", "field2":"F"}] }
2 | { "a":5, "pair":[{"field1":"C", "field2":"D"},{"field1":"E", "field2":"F"}] }
3 | { "a":8, "pair":[{"field1":"G", "field2":"G"},{"field1":"0", "field2":"1"},{"field1":"A", "field2":"A"}] }
4 | { "a":1, "pair":[{"field1":"F", "field2":"T"},{"field1":"C", "field2":"D"},{"field1":"0", "field2":"1"}] }
5 | { "a":1, "pair":[{"field1":"A", "field2":"B"}] }
After updating the rows, the values would be:
Id| ArrayColumn
--------------------------------------------------------------------------------------------
1 | { "a":1, "pair":[{"field1":"C", "field2":"D"},{"field1":"E", "field2":"F"}] }
2 | { "a":5, "pair":[{"field1":"C", "field2":"D"},{"field1":"E", "field2":"F"}] }
3 | { "a":8, "pair":[{"field1":"G", "field2":"G"},{"field1":"A", "field2":"A"}] }
4 | { "a":1, "pair":[{"field1":"F", "field2":"T"},{"field1":"C", "field2":"D"}] }
5 | { "a":1, "pair":[{"field1":"A", "field2":"B"}] }
I tried with JSON_TREE but can't make it work.
I was thinking that the first step would be to select all the rows that contain that value, I retreived them using these 2 ways:
With LIKE operator searching for the stringified form:
select Id, json_extract(json(par), '$.pair') as pair from Table pair like '%{"field1":"0","field2":"1"}%'
Using json_tree
select Id, value from Table, json_tree(Table.ArrayColumn, '$.pair' ) where json_extract(value, '$.field1' ) = '0' AND json_extract(value, '$.field2' ) = '1'
I tried using json_remove with this small example but no luck:
SELECT json_remove('[{"field1":"1","field2":"0"},{"field1":"A","field2":"B"}]', '${"field1":"1","field2":"0"}' )
I tried using json_remove but had no luck.
Thank you
For this sample data the simplest way to do this is to treat the json column as a string and use string functions to remove the value that you want:
UPDATE tablename
SET ArrayColumn = REPLACE(REPLACE(REPLACE(ArrayColumn, ']', ',]'), '{"field1":"0", "field2":"1"},', ''), ',]', ']')
WHERE ArrayColumn LIKE '%{"field1":"0", "field2":"1"}%';
See the demo.

How concatenate two filtered values in vue.js?

I need to concatenate two filtered items in vue.js.
<input
:value="startDate | dateFormat + '-' + endDate | dateFormat"
/>
How could this be possible?
This one should work
data() {
return {
fullDate: `${this.$options.filters.dateFormat(this.startDate)} - ${this.$options.filters.dateFormat(endDate)}`,
}
},
or the computed variant as suggested by Alberto (if your data changes, this one will be re-computed, data won't)
computed: {
fullDate() {
return `${this.$options.filters.dateFormat(this.startDate)} - ${this.$options.filters.dateFormat(this.endDate)}`
},
},
Then, finally
<input :value="fullDate" />
Alternatively you can stick with using a filter and just provide the two dates as array or object and create the string inside the filter function:
Use as object
<input :value="{ startDate: '2020-10-10', endDate: '2021-01-01' } | dateRange"/>
...
Vue.filter("dateRange", ({ startDate, endDate }) => `${startDate} - ${endDate}`);
Use as array
<input :value="['2020-10-10', '2021-01-01'] | dateRange" />
...
Vue.filter("dateRange", ([startDate, endDate]) => `${startDate} - ${endDate}`);
https://codesandbox.io/s/icy-monad-kdy6j?file=/src/App.vue:0-705

Totaling a Summary Line in Data Table

I hve a sumField method which totals values in a given column:
sumField (key) {
let total = 0
const sum = this.tableName.reduce((acc, cur) => {
return (total += +cur[key])
}, 0)
return sum
}
Inside my data table I call sumField to produce a rolling total of the values in a specific column of my data table:
<template v-slot:[`body.append`]="{headers}">
<tr class="summary">
<td v-for="(header,i) in headers" :key="i">
<div v-if="header.value == 'COL HEADER 1'">
{{ sumField('COL HEADER 1') }}</div>
<div v-else-if="header.value == 'COL HEADER 2'">
{{ sumField('COL HEADER 2') }}</div>
</td>
</tr>
</template>
This is presented on screen as an additional line of the data table, and the values change depending on the filters applied to the table.
Is there a way to sum the values calculated, and show this as a rolling total value also?
Got a solution which I hope might provide some help to others in the future!
Started by creating a new function:
sumTot (col1, col2) {
var one = col1
var two = col2
var tot = col1 + col2
return tot
}
Then I called sumTot giving the arguments of the individual sumField calls:
{{ sumTotal(sumField ('COL HEADER 1'), sumField ('COL HEADER 2')) }}
That gives me a dynamically updated running total value.

How to traverse through Dynamic Object of Arrays in VueJS

I have an object with arrays which is nothing but JSON reply from server which I converted into Object and now it looks like this (but lot of values into it):-
Object_return:{
name:[1,25,2,24,3,78],
age:[2,34,4,78]
}
here name and age is dynamic coming from the server, so I do not know what exact values coming there so I can not refer it while iterating through the for loop
<th v-for = "item in Object_return.name">
and also I want to show this in a DataTable so the first row should looks like this
------------------
1 25
-------
name 2 24
-------
3 78
--------------------
second row
---------------------
2 34
-------
age 4 78
------------------------
and so on and so forth for all the values coming from the server
Does someone have an idea how to do this
You can iterate over an object and get the key value as the second argument.
<tr v-for="val, key in Object_return">
Here, key will be the name of the property.
Then, since you want to group the arrays in pairs, I suggest a computed property to massage the data into the format you want.
Here is a working example.
console.clear()
new Vue({
el: "#app",
data:{
serverData: {
name:[1,25,2,24,3,78],
age:[2,34,4,78]
}
},
computed:{
massaged(){
return Object.keys(this.serverData).reduce((acc, val) => {
// split each array into pairs
const copy = [...this.serverData[val]]
let pairs = []
while (copy.length > 0)
pairs.push(copy.splice(0, 2))
// add the paired array to the return object
acc[val] = pairs
return acc
}, {})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<table>
<tr v-for="val, key in massaged">
<td>{{key}}</td>
<td>
<table>
<tr v-for="pair in val">
<td>{{pair[0]}}</td>
<td>{{pair[1]}}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>

Vue v-for changing from version 1 to version 2

I'm learning Vue.js and found this fiddle that does exactly what I want to do.
Here is the fiddle: https://jsfiddle.net/os7hp1cy/48/
I integrated this and am getting this error:
invalid expression: v-for="user in users | filterBy searchKey | paginate"
So I've done some digging and I see it has changed from version 1 to 2. However, I don't know how to fix this.
<li v-for="user in users | filterBy searchKey | paginate">{{ user.name }}</li>
I would like to replace this with something that Vue 2 will support and will work the same way.
As of Vue version 2, filters can only be used inside text interpolations ({{ }} tags). See the documentation for migrating from Vue version 1.
You can use a computed property to filter the users and use that computed property in the v-for directive instead:
computed: {
filteredUsers: function() {
let key = this.searchKey.toUpperCase();
return this.users.filter((user) => {
return user.name.toUpperCase().indexOf(key) !== -1
})
},
paginatedUsers: function() {
var list = this.filteredUsers;
this.resultCount = list.length
if (this.currentPage >= this.totalPages) {
this.currentPage = this.totalPages
}
var index = this.currentPage * this.itemsPerPage
return list.slice(index - 1, index - 1 + this.itemsPerPage)
}
}
<li v-for="user in paginatedUsers">{{ user.name }}</li>
Also, when using v-for to generate a range of numbers like you do for your page numbers, Vue version to starts the index at 1 instead of 0. So, you'll need to update the logic depending on a starting index of 0 as well.
Here's a working fiddle.