Reactjs:如何缩减对象数组以获得总和

wn9m85ua  于 2022-12-29  发布在  React
关注(0)|答案(2)|浏览(122)

我有一个对象数组,我想用信用额的总和按描述分组。我试过我的代码,但它不起作用。它有什么问题吗?
我的代码:

var result1=[]
   entries.reduce((res, value) => {
       if (!res[value.description]) {
           res[value.description] = {description: value.description, credit: 0}
           result1.push(res[value.description])
       }
       
       res[value.description].credit= (parseFloat(value.credit) +
       parseFloat(res[value.description].credit)).toFixed(2)
      
       return res
      
   }, {});

   let analysisByDescStr = result1.map((str) => (
        <div>
            {str.description|| ""} =
            {str.credit|| ""}
        </div>
    ));

pf对象数组:

{description: 'GOOGLE *Google', credit: '1.99', category: 'TELECOM'}
{description: 'AMZN Mktp #0998', credit: '20.65', category: 'MERCHANDISE'}
{description: 'AMZN Mktp #06778', credit: '70.68', category: 'MERCHANDISE'}
{description: 'OLIVE YOUNG', credit: '60.03', category: 'MERCHANDISE'}
{description: 'SAFEWAY #0982', credit: '22.97', category: 'GROCERY'}
{description: 'PEET'S #11702', credit: '7.05', category: 'COFFEE'}
{description: 'SAFEWAY #0983', credit: '20.00', category: 'GROCERY'}
{description: 'AMZN Mktp #0234', credit: '-18.62', category: 'MERCHANDISE'}

我的预期结果:

AMZN Mktp=72.71
GOOGLE *Google=1.99
OLIVE YOUNG=60.03
PEET'S=7.05
SAFEWAY=42.97
d6kp6zgx

d6kp6zgx1#

您可以使用reduce并将所需的任何变换应用于item.description,以匹配预期的标注

const result = list.reduce((acc, item) => {
  const label = item.description.substring(0, 7);
  return {
    ...acc,
    [label]: (acc[label] ?? 0) + Number(item.credit)
  }
}, {})
y4ekin9u

y4ekin9u2#

使用reduce函数

const list = [{description: 'GOOGLE *Google', credit: '1.99', category: 'TELECOM'},
{description: 'AMZN Mktp', credit: '20.65', category: 'MERCHANDISE'},
{description: 'AMZN Mktp', credit: '70.68', category: 'MERCHANDISE'},
{description: 'OLIVE YOUNG', credit: '60.03', category: 'MERCHANDISE'},
{description: 'SAFEWAY #0982', credit: '22.97', category: 'GROCERY'},
{description: 'PEETS #11702', credit: '7.05', category: 'COFFEE'},
{description: 'SAFEWAY #0983', credit: '20.00', category: 'GROCERY'},
{description: 'AMZN Mktp', credit: '-18.62', category: 'MERCHANDISE'}]

const result = list.reduce((acc, item) => {
  
  if(acc[item.description]){
    acc[item.description] += Number(item.credit)
  }else{
     acc[item.description] = Number(item.credit)
  }
  
  return acc
}, {})

console.log(result)

相关问题