ember.js 返回Ember JS当月费用合计

kse8i1jr  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(169)

我想得到我的费用总额,但要按本月进行筛选。

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', 'thisMonth')函数不起作用。我以为这会简单得多,但事实并非如此。使用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')
});
dwbf0jvd

dwbf0jvd1#

我不是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')

相关问题