简体   繁体   中英

how to get sum of array in vue js using computed?

this the resul of my query

{1: {deduction: 625}, 2: {deduction: 500}, 3: {deduction: 2500}, grandTotal: 8460, otTotal: 50,…}
1: {deduction: 625}
2: {deduction: 500}
3: {deduction: 2500}
allowance: 0
grandTotal: 8460
otTotal: 50

my computed in vue I got an error here "TypeError: this.grand.reduce is not a function"

totaldeduct(){
return this.grand.reduce((acc, item)=>{
return acc+ Number(item.deduction)
},0)
}

Reduce() is an array function in javascript. You either want to use forEach for your object or rewrite it to an array.

 const data = [ { deduction: 625 }, { deduction: 500 }, { deduction: 2500 }, { grandTotal: 8460 }, { otTotal: 50 }, ]; function totaldeduct(data) { return data.reduce((acc, item) => { if(item.deduction) return acc + item.deduction; else return acc }, 0); } let reduced = totaldeduct(data); console.log(reduced);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM