Javascript 返回余烬JS中当月的费用总额
我想获取我的费用总额,但按当前月份进行过滤Javascript 返回余烬JS中当月的费用总额,javascript,ember.js,Javascript,Ember.js,我想获取我的费用总额,但按当前月份进行过滤 expenses: computed('transactions.length', 'transactions.@each.amount', function() { return this.get('transactions').filterBy('typeOfT','expense').sortBy('date') }), filteredExpenses: computed('expenses.length', 'expenses.@eac
expenses: computed('transactions.length', 'transactions.@each.amount', function() {
return this.get('transactions').filterBy('typeOfT','expense').sortBy('date')
}),
filteredExpenses: computed('expenses.length', 'expenses.@each.amount', function() {
let thisMonth = new Date().getFullYear()+'-'+(new Date().getMonth()+1)
return this.get('expenses').filterBy('date', 'thisMonth').mapBy('amount').reduce((a, b) => a + b, 0)
}),
因此,尝试filterBy('date','thismonly')
函数无效。我原以为这会容易得多,但事实并非如此。使用mapBy('amount')
和reduce((a,b)=>a+b,0)
我可以得到所有费用的数组,并使用函数计算总和
我的模型:
export default Model.extend({
category: DS.attr(),
name: DS.attr(),
description: DS.attr(),
amount: DS.attr(),
date: DS.attr(),
typeOfT: DS.attr(),
user: DS.belongsTo('user')
});
我不是100%支持当月筛选(可能需要一些调整),但通常这会给你当月的费用:
import { computed } from '@ember/object';
import { filterBy, mapBy, sum } from '@ember/object/computed';
// first get all of your expenses in an array by filtering on `typeOfT`:
expenses: filterBy('transactions', 'typeOfT', 'expense'),
// then filter expenses by the current month
currentMonthExpenses: computed('expenses', function() {
return this.get('expenses').filter(expense => {
return new Date(expense.get('date')).getMonth() === new Date().getMonth();
});
}),
// now map all of this month's expenses by their amounts:
currentMonthExpenseAmounts: mapBy('currentMonthExpenses', 'amount'),
// now sum all of the current month's expense amounts:
sumOfCurrentMonthExpenses: sum('currentMonthExpensesAmounts')
你能发布你的数据吗?@stevenelberger我在上面添加了这个模型