val*_*eru 3 javascript reactjs
我正在使用地图在我的应用程序中呈现 op 产品列表。像这样:
<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>;
Run Code Online (Sandbox Code Playgroud)
状态命令加载了这段代码:
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));
Run Code Online (Sandbox Code Playgroud)
现在我想按类别对产品进行分组并按如下方式输出:
- <h3>category 1</h3>
- image - productname - quantity
- image - productname - quantity
- <h3>category 2</h3>
- image - productname - quantity
- image - productname - quantity
Run Code Online (Sandbox Code Playgroud)
等等
我不知道如何按类别对产品进行分组,并按类别排序显示它们,并将类别名称作为每个产品组的标题。我希望有人能进一步帮助我。
更新
我设法将数组分组为
但我无法让它用地图或其他东西渲染。
类别名称目前是数字,但这可能会在以后发生。
第一步是使用以下方法对数据进行分组:对 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'},
]
}];
Run Code Online (Sandbox Code Playgroud)
.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>
))
}
Run Code Online (Sandbox Code Playgroud)