gpt4 book ai didi

javascript - Reactjs objectlist groupby 和映射

转载 作者:行者123 更新时间:2023-11-30 11:20:04 24 4
gpt4 key购买 nike

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

<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

等等

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

更新

我设法将数组分组到

enter image description here

但我无法使用 map 或其他方式渲染它。

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

最佳答案

您的第一步是使用类似于 What is the most efficient method to groupby on a JavaScript array of objects? 的方式对您的数据进行分组或 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>
))
}

关于javascript - Reactjs objectlist groupby 和映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50148658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com