有没有更好的方法来查找数组中对象的属性
Is there a better way to find properties of object in an array
我正在提高我的编码技能。我写了一个代码,它工作正常。但我认为它可以写得更好。
这是代码和一些解释,
我使用下面的代码来 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
我正在提高我的编码技能。我写了一个代码,它工作正常。但我认为它可以写得更好。
这是代码和一些解释,
我使用下面的代码来 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