到目前为止我正在尝试的代码

let data = [
{size: 1180160, category: "Keswick", index: 1},
{size: 1059328, category: "HCOPA", index: 2},
{size: 30720, category: "HCOPA", index: 3},
{size: 493056, category: "Darhan Saluja", index: 4},
{size: 267776, category: "CRSA", index: 5},:
{size: 328704, category: "Arundel", index: 6}
{size: 73216, category: "Arundel", index: 7}

data.forEach((product, index) => {

           let size = 0;
           if (product.category !== lastCategory) {
             size = product.size + size;
             rows.push(
                <ProductCategoryRow size={size}
                                    category={product.category}
                                    key={product.category}/>
            );
        }
        rows.push(
            <ProductRow
                product={product}
                key={product.name} index={index}/>
        );
        lastCategory = product.category;

    });


我要计算具有相同类别的尺寸。这样就可以作为道具的传递对象

最佳答案

我建议您首先创建一个新对象,其中包含所需的所有数据以及所需的属性的总和,然后使用该对象执行所需的逻辑。

请查看下面的代码段,并根据需要进行调整。



let data = [
{size: 1180160, category: "Keswick", index: 1},
{size: 1059328, category: "HCOPA", index: 2},
{size: 30720, category: "HCOPA", index: 3},
{size: 493056, category: "Darhan Saluja", index: 4},
{size: 267776, category: "CRSA", index: 5},
{size: 328704, category: "Arundel", index: 6},
{size: 73216, category: "Arundel", index: 7}]

const dataWithSum = data.reduce((acc, current) => {
  acc[current.category] = acc[current.category] ? acc[current.category] + current.size : current.size;
  return acc
}, {})

console.log(dataWithSum)

07-24 17:50
查看更多