json 使用javascript/react按月过滤数组并获取每个月的总和

7gs2gvoe  于 2023-01-06  发布在  Java
关注(0)|答案(1)|浏览(164)

我有一个包含多个对象的数组,每个对象都有一个日期、数量和ID作为键。
我想按月对所有对象进行分组,然后返回每个月的金额键的总和。
这是我的第一个方法,但我很确定这不是正确的方法。
我手动定义每个月的开始和结束。
有没有其他更动态的方法?
1 -获取每个月的开始和结束日期
2 -按月对数组分组,不使用lodash(我愿意使用moment.js)
3 -对每个月的值求和
3 -返回月份名称+总计

json中的数组结构

"expenses": [
    {
      "amount": 5.97,
      "date": "09/01/2022",
      "id": 1
    },
]

React中的逻辑

const MonthsTotal = ({ expenses }) => {
  let novemberTotal = 0;
  let decemberTotal = 0;

  expenses
    .filter((items) => {
      return items.date >= "11/01/2022" && items.date <= "11/31/2022";
    })
    .forEach((item) => {
      novemberTotal += item.amount;
    });

  expenses
    .filter((items) => {
      return items.date >= "12/01/2022" && items.date <= "12/31/2022";
    })
    .forEach((item) => {
      decemberTotal += item.amount;
    });

React中的输出

这就是我输出数据的方式

return (
 <Box>
  <Card variant="outlined">
    <div> November </div>
    <div>{novemberTotal}</div>
  </Card>
 </Box>

 <Box>
  <Card variant="outlined">
    <div>December</div>
    <div>{decemberTotal}</div>
  </Card>
 </Box>
)
export default MonthsTotal;
toe95027

toe950271#

我首先将费用按月份分组,然后合计它们的金额,在这个例子中我使用了lodash和date-fns,但是可以用任何其他库来替换它们。

import { format } from 'date-fns';
import groupBy from 'lodash/groupBy';
import sumBy from 'lodash/sumBy';

const expenses = [
  {
    amount: 5.97,
    date: '09/01/2022',
    id: 1,
  },
  {
    amount: 5.97,
    date: '09/02/2022',
    id: 1,
  },
  {
    amount: 5.97,
    date: '10/01/2022',
    id: 3,
  },
];

const groups = groupBy(expenses, (entry) => {
  return format(new Date(entry.date), 'LLLL');
});

const months = Object.entries(groups).map((entry) => {
  const [key, values] = entry;

  return {
    name: key,
    total: sumBy(values, 'amount'),
  };
});

// [
//   { name: 'September', total: 11.94 },
//   { name: 'October', total: 5.97 }
// ]

接下来,您可以将所有月份传递给React组件,并对它们进行循环

function MonthsTotal(props) {
  const { months } = props;

  return (
    <>
      {months.map((month) => (
        <Box key={month.name}>
          <Card variant="outlined">
            <div>{month.name}</div>
            <div>{month.total}</div>
          </Card>
        </Box>
      ))}
    </>
  );
}

<MonthsTotal months={months} />;

相关问题