简体   繁体   English

有没有更好的方法在数组中查找 object 的属性

[英]Is there a better way to find properties of object in an array

I am improving my coding skills.我正在提高我的编码技能。 I wrote a code and it works fine.我写了一个代码,它工作正常。 But I think it could be written better.但我认为它可以写得更好。

Here is are the codes and a bit of explanation,这是代码和一些解释,

I use the code below to setState for an array named transactions我使用下面的代码为名为setState的数组设置状态

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

I needed to sum an object in the transaction array so I wrote this code.我需要在事务数组中求和一个 object,所以我编写了这段代码。

let a = transactions,
  total = 0;

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

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

Then, use the code by calling it like this {total}然后,通过像这样调用它来使用代码 {total}

<h1>{total}</h1>

Then I needed the value of a property in the last object within the array so I wrote this然后我需要数组中最后一个 object 中的属性值,所以我写了这个

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

console.log(first);

const payment = { ...first };

And subsequently used it like this随后像这样使用它

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

The code works fine Please any idea on how to write this better.代码工作正常请任何关于如何更好地编写它的想法。 Thanks谢谢

This works better for me.这对我来说效果更好。 thanks,谢谢,

 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 @Tr1stan @Emile Bergeron

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM