【JS】Array.reduce对数组中的指定key求和
Array.prototype.sumFields = function(...fields) { return this.reduce((acc, item) => { fields.forEach(field => { acc[field] = (acc[field] || 0) + (Number(item[field]) || 0); }); return acc; }, {}); } const items = [ { a: 10, b: 20, c: null }, { a: 15, b: 25, c: '35' }, { a: 5, b: 20, c: 8.5 }, ]; const acc = items.sumFields('a', 'c'); console.log(acc)
运行结果:
zcm@TXK MINGW64 /d/sysProfile/Desktop $ node a.js { a: 30, c: 43.5 }