首页 > 解决方案 > 有没有更好的方法来查找数组中对象的属性

问题描述

我正在提高我的编码技能。我写了一个代码,它工作正常。但我认为它可以写得更好。

这是代码和一些解释,

我使用下面的代码来setState创建一个名为 transactions 的数组

useEffect(() => {
  TransactionService.getTransactions().then(data => {
    setTransactions(data.transactions);
  });
}, []);

我需要对事务数组中的一个对象求和,所以我编写了这段代码。

let a = transactions,
  total = 0;

for (var i = 0; i < a.length; i++) {
  total += a[i].amount;

  console.log('total', total);
};

然后,通过像这样调用它来使用代码 {total}

<h1>{total}</h1>

然后我需要数组中最后一个对象的属性值,所以我写了这个

var array1 = transactions;
var first = array1[array1.length - 1];

console.log(first);

const payment = { ...first };

随后像这样使用它

<h1>{payment.amount}</h1>

代码工作正常请任何关于如何更好地编写它的想法。谢谢

标签: javascriptreactjsfunctionreact-propsuse-state

解决方案


这对我来说效果更好。谢谢,

    
  const lastTransaction = transactions[transactions.length - 1];
  let lastPayment = ({ ...lastTransaction }).amount;
  const today = new Date();
  let lastMonth = today.getMonth() - 1;
  let relevantYear = today.getYear();
  let thisMonth = today.getMonth();

  const lastMonthTransactions = transactions.filter(i => {
  const date = new Date(i.date);
    return date.getMonth() === lastMonth && date.getYear() === relevantYear;
  }).reduce((prev, curr) => prev + parseFloat(curr.amount), 0)

@Tr1stan @Emile Bergeron


推荐阅读