yassine j
yassine j

Reputation: 515

VueJs / Laravel. Sum of Multiple arrays in different objects

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) enter image description here

Upvotes: 1

Views: 568

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

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

Maxim
Maxim

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

Related Questions