首页 > 解决方案 > 重新排列数组中对象的结构

问题描述

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

// 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 的“卖家购物车组件”将首先呈现。

标签: javascriptreactjs

解决方案


按卖家对您的购物车商品进行分组:

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>
  );
});

推荐阅读