javascript - 重新排列数组中对象的结构
问题描述
我有一组看起来与此类似的对象:-
// The array ("shoppingCart") could contain lots of different "products", by lots of different "sellers".
const shoppingCart = [
{
product: { product: 34, seller: 1 },
quantity: 43
},
{
product: { product: 2, seller: 2 },
quantity: 65
},
{
product: { product: 7, seller: 1 },
quantity: 23
},
{
product: { product: 5, seller: 2 },
quantity: 75
}
];
我需要通过这些对象进行映射,以呈现这个所需的视图: 购物车数据呈现
我如何重组这个数组,以便它由卖方排序,然后在一个结构中进行排序,然后可以通过该结构进行映射以呈现“卖方购物车组件”,产品作为道具传递(因此它们可以映射到“产品购物车组件”稍后)?
注意:理想情况下,卖家应该按照他们在“shoppingCart”数组中出现的顺序进行组织。即,如果产品 34 包含键值对“卖家:2”,那么卖家 2 的“卖家购物车组件”将首先呈现。
解决方案
按卖家对您的购物车商品进行分组:
const shoppingCart = [
{
product: { product: 34, seller: 1 },
quantity: 43
},
{
product: { product: 2, seller: 2 },
quantity: 65
},
{
product: { product: 7, seller: 1 },
quantity: 23
},
{
product: { product: 5, seller: 2 },
quantity: 75
}
];
const groupedCart = shoppingCart.reduce((sellers, {product, quantity}) => {
// stringify seller so "insertion" order is maintained in
// object, i.e. numerical key are sorted numerically,
// non-numerical are not
const sellerKey = `${product.seller}`;
if (!sellers[sellerKey]) {
sellers[sellerKey] = {
products: [],
};
}
sellers[sellerKey].products.push({
product: product.product,
quantity: quantity,
});
return sellers;
}, {});
console.log(groupedCart);
在您的反应组件中,您将映射到分组购物车,类似于:
Object.entries(groupedCart).map(([seller, { products }])=> {
return (
<div>
<p>Seller {seller}</p>
{
products.map(({ product, quantity }) => (
<div>Product {product} {quantity}</div>
))
}
</div>
);
});
推荐阅读
- c++ - 无法理解函数返回的类型
- discord - Nuke 命令 discord.py
- python - 我正在尝试使用两个端点 (x1,y1)(x2,y2) 为一条线设置动画,但 line.set_data() 函数似乎没有更新 x 和 y 坐标
- javascript - 连接集合查看器 Firebase
- firebase - 如何使用 Firebase 身份验证获取 onAuthStateChanged 流?
- java - “主要”java.lang.ClassCastException:[Ljava.lang.Comparable; 不能转换为 [LNode;
- python - ZeroDivisionError:在 chess.py 中除以零
- python - Swift 中的简单线性插值
- node.js - 如何使用 node.js 仅更新 JSON 文件中的一个键
- android - zipalign:符号查找错误:/usr/lib/x86_64-linux-gnu/android/libbacktrace.so.0:未定义符号:_ZN11unwindstack12ElfInterfaceD2Ev