首页 > 解决方案 > Reactjs objectlist groupby 和 map over

问题描述

我正在使用地图在我的应用程序中呈现列表操作产品。像这样:

<div className={`content ${isLoading ? 'is-loading' : ''}`}>
  <div className="panel">
    {!isLoading && orders.length > 0
      ? orders.map((order, index) => {
          const { productname, image, quantity, orderid, category } = order;
          return (
            <div className="product" key={orderid}>
              <div className="plaatjediv" onClick={this.toggleModal.bind(this)}>
                <img
                  className="img-responsive"
                  data-itemIndex={index}
                  src={image}
                />
              </div>
              <div className="productInfo">
                <p>{productname}</p>
                <p>Aantal: {quantity}</p>
              </div>
              <div className="bdone">
                <button
                  className="btn btn-lg btn-default btndone"
                  data-itemIndex={index}
                  onClick={this.handleDoneAction}
                >
                  Done
                </button>
              </div>
            </div>
          );
        })
      : null}
  </div>
</div>;

状态订单加载了这段代码:

fetch('http://localhost:54408/api/orders/all/testing-9!8-7!6/' + todayy)
  .then(response => response.json())
  .then(parsedJSON =>
    parsedJSON.map(product => ({
      productname: `${product.ProductName}`,
      image: `${product.Image}`,
      quantity: `${product.Quantity}`,
      category: `${product.Category}`,
      orderid: `${product.OrderId}`,
    }))
  )
  .then(orders =>
    this.setState({
      orders,
      isLoading: false,
    })
  )
  .catch(error => console.log('parsing failed', error));

现在我想按类别对产品进行分组并像这样输出:

 - <h3>category 1</h3>
    - image - productname - quantity
    - image - productname - quantity
 - <h3>category 2</h3>
   - image - productname - quantity
   - image - productname - quantity

等等

我不知道如何按类别对我的产品进行分组,并按类别排序显示它们,并将类别名称作为每个产品组的标题。我希望有人可以进一步帮助我。

更新

我设法将数组分组到

在此处输入图像描述

但我不能让它用地图或其他东西渲染。

类别名称现在是数字,但这可能会在以后发生。

标签: javascriptreactjs

解决方案


您的第一步是使用类似的方法对数据进行分组,在 JavaScript 对象数组上分组的最有效方法是什么?lodash groupBy

然后,您的数据将如下所示:

const data = [{
  category: 'category1',
  orders: [
    {productname: 'pn1', image: 'img1', quantity: 1, orderid: 'ord1'},
    {productname: 'pn2', image: 'img2', quantity: 2, orderid: 'ord2'}
  ]
}, {
  category: 'category2',
  orders: [
    {productname: 'pn3', image: 'img3', quantity: 1, orderid: 'ord3'},
    {productname: 'pn4', image: 'img4', quantity: 2, orderid: 'ord4'},
    {productname: 'pn5', image: 'img5', quantity: 2, orderid: 'ord4'},
  ]
}];

.map然后你可以在你的渲染方法中使用两个嵌套:

render() {
  return Object.keys(data).map(cat => (
    <div>
      <h3>{cat}</h3>
      {data[cat].map(ord => (
        <div>
          <div>{ord.productname}</div>
          <div>{ord.image}</div>
          <div>{ord.quantity}</div>
          <div>{ord.orderid}</div>
        </div>
      ))}
    </div>
  ))
}

推荐阅读