javascript - 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
等等
我不知道如何按类别对我的产品进行分组,并按类别排序显示它们,并将类别名称作为每个产品组的标题。我希望有人可以进一步帮助我。
更新
我设法将数组分组到
但我不能让它用地图或其他东西渲染。
类别名称现在是数字,但这可能会在以后发生。
解决方案
您的第一步是使用类似的方法对数据进行分组,在 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>
))
}
推荐阅读
- jquery - 数据表嵌套表错误404
- python - 如何用每列的平均值填充缺失值
- ios - 为什么 UIView 框架上的 observable 只在订阅后触发一次
- c# - 如何获取自动化帐户 Webhook 以在 ASP.NET 中返回值
- python - 字符串的数据框列中没有值,类中的错误
- reactjs - 为什么 ReactJS 在 MVC 中只有 V?
- php - PHP没有从AJAX调用发送响应文本
- php - PHP表单Action添加$变量
- oracle11g - 如何提高具有非常快查询(在 PL/SQL 开发人员处运行)的 JpaRepository 慢速方法性能?
- html - 有没有解决背景图像不完整的方法