我有今年的月值数组,其中包含来自gsheet的数据:
// @require file://C:\Blah\bleh\userscript.user.js
我想像这样总结每个月的总价值:
2019 - Mar - 3
2019 - Mar - 1
2019 - Feb - 1
2019 - Feb - 1
2019 - Feb - 1
2019 - Feb - 1
2019 - Feb - 3
2019 - Feb -
2019 - Feb - 2
2019 - Feb - 1
2019 - Feb - 1
2019 - Jan - 1
2019 - Jan - 1
2019 - Jan - 1
2019 - Jan - 1
现在这是我的代码:
2019 - Mar - 4
2019 - Feb - 11
2019 - Jan - 4
我如何求和每月值?我在哪里进行手术?在<div class="row" id="list">
<div v-for="entry in entries" v-if="entry.gsx$regionofincident.$t === 'Mediterranean'">
<span>{{entry.gsx$reportedyear.$t}} - {{entry.gsx$reportedmonth.$t}} - {{entry.gsx$numberdead.$t}}</span>
</div>
</div>
或js
中?
答案 0 :(得分:2)
您可以使用computed property来过滤地中海美食,然后使用Array.prototype.reduce
来计算结果:
computed: {
medEntries() {
const tally = this.entries
// only process Mediterranean items
.filter(entry => entry.gsx$regionofincident.$t === 'Mediterranean')
// tally results
.reduce((obj, entry) => {
const key = entry.gsx$reportedyear.$t + entry.gsx$reportedmonth.$t
const val = obj[key]
const numDead = Number(entry.gsx$numberdead.$t || 0)
if (val) {
val.gsx$numberdead.$t = Number(val.gsx$numberdead.$t) + numDead
} else {
obj[key] = entry
}
return obj
}, {})
return Object.values(tally)
}
}
然后将模板中的entries
替换为计算出的属性名称(medEntries
):
<div v-for="entry in medEntries">...</div>
const entry = (year, month, numDead) => ({
gsx$regionofincident: { $t : 'Mediterranean' },
gsx$reportedmonth: { $t: month },
gsx$reportedyear: { $t: year },
gsx$numberdead: { $t: numDead },
})
const entries = [
entry('2019', 'Mar', '3'),
entry('2019', 'Mar', '1'),
entry('2019', 'Feb', '1'),
entry('2019', 'Feb', '1'),
entry('2019', 'Feb', '1'),
entry('2019', 'Feb', '1'),
entry('2019', 'Feb', '3'),
entry('2019', 'Feb'),
entry('2019', 'Feb', '2'),
entry('2019', 'Feb', '1'),
entry('2019', 'Feb', '1'),
entry('2019', 'Jan', '1'),
entry('2019', 'Jan', '1'),
entry('2019', 'Jan', '1'),
entry('2019', 'Jan', '1'),
]
new Vue({
el: '#app',
data() {
return {
entries
}
},
computed: {
medEntries() {
const tally = this.entries
.filter(entry => entry.gsx$regionofincident.$t === 'Mediterranean')
.reduce((obj, entry) => {
const key = entry.gsx$reportedyear.$t + entry.gsx$reportedmonth.$t
const val = obj[key]
const numDead = Number(entry.gsx$numberdead.$t || 0)
if (val) {
val.gsx$numberdead.$t = Number(val.gsx$numberdead.$t) + numDead
} else {
obj[key] = entry
}
return obj
}, {})
return Object.values(tally)
}
}
})
<script src="https://unpkg.com/vue@2.6.10"></script>
<div id="app">
<div v-for="entry in medEntries">
<span>{{entry.gsx$reportedyear.$t}} - {{entry.gsx$reportedmonth.$t}} - {{entry.gsx$numberdead.$t}}</span>
</div>
</div>