javascript - 有没有更好的方法来查找数组中对象的属性
问题描述
我正在提高我的编码技能。我写了一个代码,它工作正常。但我认为它可以写得更好。
这是代码和一些解释,
我使用下面的代码来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>
代码工作正常请任何关于如何更好地编写它的想法。谢谢
解决方案
这对我来说效果更好。谢谢,
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
推荐阅读
- automation - 如何在botium的convo文件中的#begin中声明两个变量
- excel - 在 Microsoft Word 中使用 VBA 查找 Excel 工作表中使用的最后一列
- python - 为什么我无法使用 try-except 将 str 转换为 int?
- r - Rmarkdown PDF中的绘图(ggplot2)被裁剪
- ios - Fastlane import_certificate 找不到文件
- flutter - Flutter:如何使用“通用”类构造函数?
- r - 按 r 中的总收入计算每个月的收入
- python-3.x - 无法理解为什么函数中的基本循环获取字符串并打印字母直到字符串中的第一个数字不起作用
- sql - SQL 选择重复问题
- python-3.x - 尴尬的数组;根据索引列表从每一行中选择一个项目