0

I have an array of objects that looks similar to this:-

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

I need to map through these objects, in order to render this desired view: shopping cart data rendered

How can I restructure this array so that it is sorted by Seller and in a structure which can then be mapped through in order to render "Seller Cart Component(s)", with the products passed through as props (so they can be mapped into "Product Cart Component(s)" later on)?

Note: ideally the sellers should be organised in the order in which they appear in the "shoppingCart" array. i.e. if product 34 were to contain the key-value pair "seller: 2", then seller 2's "Seller Cart Component" would render first.

3 Answers 3

1

Group your cart items by seller:

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

In your react component you'll map over the grouped cart, similar to:

Object.entries(groupedCart).map(([seller, { products }])=> {
  return (
    <div>
      <p>Seller {seller}</p>
      {
        products.map(({ product, quantity }) => (
          <div>Product {product} {quantity}</div>
        ))
      }
    </div>
  );
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Drew! Works great. Unless I'm missing something, there is a typo. "sellerKey" does need to be declared as a variable. I can't edit it, so maybe you could? Sends virtual coffee and pizza
@AgileDom Ack, you are correct. Thanks! Interesting it still yields the correct values.
0

I'd do something like this:

const sellers = shoppingCart.reduce((sellers, entry) => {
  let sellerMatch = sellers.find(seller => seller.id === entry.product.seller);
  if (!sellerMatch) {
    sellerMatch = { 
      id: entry.product.seller, 
      products: [] 
    };
    sellers.push(sellerMatch);
  }
  sellerMatch.products.push({
    id: entry.product.product,
    quantity: entry.quantity
  });
  return sellers;
}, []);

console.log(sellers);

Comments

0

If you rearranged the shoppingCart as

const shoppingCart = {
  "seller 1": {
    product: { item: 34, quantity: 43 },
    product: { item: 7, quantity: 23 },
  },
  "seller 2": {
    product: { item: 2, quantity: 65 },
    product: { item: 5, quantity: 75 },
  }
};

You could access each seller and their products with for...in loop

for (let seller in shoppingCart) {
  // seller, calls the key ("seller 1" or "seller 2")
  // shoppingCart[seller], calls the sellers products ([{}, {}])
  for (let item in shoppingCart[seller]) {
    // item.product, calls the product id
    // item.quantity, calls the product quantity
  }
}

This would let you map the cart by seller, which was what you wanted in the question but would face the same problem when trying to view the products sorted by products or quantity.

1 Comment

Can't use "product" key twice in object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.