我想得到我的费用总额,但按当月筛选。

expenses: computed('transactions.length', '[email protected]', function() {
  return this.get('transactions').filterBy('typeOfT','expense').sortBy('date')
}),

filteredExpenses: computed('expenses.length', '[email protected]', 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')
});

最佳答案

我不是每月过滤的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')

关于javascript - 在Ember JS中返回当月的费用总额,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59414142/

10-13 01:03