Home > Software design >  getting sum of previous element from list VUEJS
getting sum of previous element from list VUEJS

Time:09-20

I am trying to get sum of previous element and add this to the existing list.

This is my current list:

ongoing: [
  {
    id: 'id1',
    name: 'clientName',
    productionTime: 15,
       
  },
  {
    id: 'id2',
    name: 'client',
    productionTime: '15'
 
  }
],

this is the result I want to achieve:

      ongoing: [
         {
           id: 'id1',
           name: 'clientName',
           productionTime: 15,
           sumofprevious: 15
         },
         {
           id: 'id2',
           name: 'client',
           productionTime: 15,
           sumofprevious: 30 (note: this comes from 15   15)
         }
      ],

I use vuejs 3 with Pinia.

I tried many codes/examples but this is the closest one but it doesn't work as I want it. It doesn't read productionTime from ongoing

const thisList = computed(() => {
  let array = storeOrders.ongoing.productionTime,
  
  sum = 0,
  newarray = array.map(value => sum  = value)

    return console.log(newarray)
  }) 

CodePudding user response:

You can use computed property:

const { computed, reactive } = Vue
const app = Vue.createApp({
  setup() {
    let ongoing = reactive([{id: 'id1', name: 'clientName', productionTime: 15,}, {id: 'id2', name: 'client', productionTime: '15'}])
    
    const res = computed(() => {
      let sum = 0
      return ongoing.map(o => {
        sum  =  o.productionTime
        return {...o, sumofprevious: sum}
      })
    })
    
    const add = () => {
      ongoing.push({id: Math.floor(Date.now() / 1000), name: 'name', productionTime: Math.ceil(Math.random() * 20),})
    }
    
    return { ongoing, res, add };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <button @click="add">add</button>
  <br />
  ongoing: {{ ongoing }}
  <br /><br />
  result: {{ res }}
</div>

CodePudding user response:

I would try to compute this:

const ongoing = [
  {
      id: 'id1',
      name: 'clientName',
      productionTime: 15,
      sumOfPrevious: 0,
  },
  {
      id: 'id2',
      name: 'client',
      productionTime: 15,
  }
];

const sumOfPrev = () => {
  return ongoing.map((el, i) => {
    if (i !== 0) {
      el.sumOfPrevious = ongoing[i-1].productionTime   el.productionTime;
    }
    return el;
  })
}

console.log(sumOfPrev());

  • Related