【问题标题】:Merge 2 table data and add/combine two integer fields合并 2 个表数据并添加/合并两个整数字段
【发布时间】:2021-04-12 05:06:22
【问题描述】:

我有一张数据表,其中显示了特定产品和全天购买的数量。它们作为不同的对象插入,我想添加每种产品购买的商品数量。

我的桌子是这样的

Apple 10 01/20/2021 18:30
Apple 5  01/29/2021 04:30
Apple 20 01/29/2021 07:30

但我希望它们组合成like

Apple 35

到目前为止,这就是我设置表格的方式

<Table striped="true" size="sm" style={{width: "20%"}}>
 <tbody>
  {this.state.products?.map((product, index) => (
   <tr key={`entity-${index}`}>
     <td>{product.type}</td>
     <td>{product.amount}</td>                        
   </tr>
  ))}
 </tbody>
</Table>

如何根据类型组合这些数据?

【问题讨论】:

    标签: javascript arrays object filter combinations


    【解决方案1】:

    以下是我为解决上述问题所采取的步骤。我已将状态的使用留给您根据您的要求实施。

    1. 首先,我创建了一系列水果及其相应的购买数量
    2. 创建了一套以获得独特的水果
    3. 在 JSX 中,我循环了 Set,然后通过先过滤水果名称然后使用 reduce 将数量相加来计算这些水果的总数量
    4. 这些值最终显示在表格中

    class Fruits extends Component {
      render() {
        const purchasedItems = [
          { fruit: "apple", quantity: 5 },
          { fruit: "apple", quantity: 2 },
          { fruit: "apple", quantity: 10 },
          { fruit: "mango", quantity: 5 },
          { fruit: "mango", quantity: 8 },
        ];
    
        let uniqueFruit = [...new Set(purchasedItems.map((x) => x.fruit))];
        
        return (
          <div>
            <table>
              <tbody>
                {uniqueFruit.map((fruit_name) => {
                  let total = purchasedItems
                    .filter((item) => 
                      item.fruit === fruit_name
                    )
                    .reduce((acc, curr) => acc + curr.quantity, 0);
                  return(
                  <tr>
                    <td>{fruit_name}</td>
                    <td>{total}</td>
                  </tr>)
                })}
              </tbody>
            </table>
          </div>
        );
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      相关资源
      最近更新 更多