gpt4 book ai didi

javascript - 重新排列数组中对象的结构

转载 作者:行者123 更新时间:2023-12-02 22:10:15 25 4
gpt4 key购买 nike

我有一个看起来与此类似的对象数组:-

// 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
}
];

我需要映射这些对象,以便渲染所需的 View : shopping cart data rendered

我如何重组这个数组,以便它按卖家排序,并在一个结构中,然后可以映射该结构以呈现“卖家购物车组件”,并将产品作为 Prop 传递(这样它们就可以稍后映射到“产品购物车组件”)?

注意:理想情况下,卖家应按照其在“shoppingCart”数组中出现的顺序进行组织。即,如果产品 34 包含键值对“seller: 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);

在您的 react 组件中,您将映射分组的购物车,类似于:

Object.entries(groupedCart).map(([seller, { products }])=> {
return (
<div>
<p>Seller {seller}</p>
{
products.map(({ product, quantity }) => (
<div>Product {product} {quantity}</div>
))
}
</div>
);
});

关于javascript - 重新排列数组中对象的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583576/

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