Reputation: 515
i use this code to display all persons i have.
<div class="col-md-3" v-for="person in persons">
</div>
//Each Person is an Object. in Each Object there are multiple objects(Money Given). i Need to Calculate the sum of total amount (Array) existing in those objects (All money given to each person)
//Like to say, all the credits relative to each Person.
I use to do that with Php, but how can i do that with computed ?
Vuejs code :
var app = new Vue({
el: '#app',
data: {
persons:[],
},
methods: {
getPersons (),
},
Thanks you !
Here is a sample of persons. multiples objects, and inside each object, usercashfloats with multiple objects i need to calculate the amount . (Amount exist in each these objects)
Upvotes: 1
Views: 568
Reputation: 1
Your computed
property should be like :
computed:{
personsWithAount(){
const reducer = (accumulator, currentValue) => accumulator.amount + currentValue.amount;
return this.persons.map((pers)=>{
let p=pers;
if(pers.usercashfloat.length==0){
p.totalAmount=0;
}else if(pers.usercashfloat.length==1){
p.totalAmount=pers.usercashfloat[0].amount;
}else{
p.totalAmount=pers.usercashfloat.reduce(reducer);
}
return p;
});
}
}
reduce
function doc
and in your template you will have something like :
<div class="col-md-3" v-for="person in personsWithAmount">
{{person.totalAmount}}
</div>
Upvotes: 2
Reputation: 2401
It could be like this:
<div class="col-md-3" v-for="person in preparedPersons">
</div>
var app = new Vue({
el: '#app',
data: {
persons:[],
},
computed: {
preparedPersons : function() {
return this.persons.map(
(p) => {
return {
...p,
sumOfAmount: p.usercashfloat.reduce(
(acc, cur) => acc.amount + cur.amount
)
};
}
)
}
},
methods: {
getPersons (),
},
Upvotes: 2