【问题标题】:What is the best way to split data based on product owners in reactjs or nodejs在 reactjs 或 nodejs 中根据产品所有者拆分数据的最佳方法是什么
【发布时间】:2022-07-04 12:13:41
【问题描述】:

我需要一些想法!

是否有任何可能的方法来根据供应商电子邮件分隔用户订单?我正在尝试开发一个多供应商项目,供应商可以上传产品。当用户从不同的商店订购时,我正在尝试根据供应商电子邮件拆分订单。

假设客户尝试从 x 供应商和 y 供应商购买产品。当客户订购产品时,数据看起来像下面的数组对象。很难在他们的仪表板中显示订购您产品的供应商订单。因此,我尝试根据电子邮件拆分订单,拆分订单时,金额将在paymentDetail.amount 的供应商之间分配。

[
        {
            _id: "622d70a49bd88b1599026318",
            products: [
                {
                    _id: "6223186e2278d4e502f5264a",
                    title: "Product number 1",
                    price: 600,
                    cartQuantity: 1,
                    vendor: {email: "vendor1@gmail.com"}
                },
                {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "vendor2@gmail.com"
                    }
                },
                 {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "vendor2@gmail.com"
                    }
                },
            ],
            paymentDetails: {
                createdId: 1647145079,
                date: "Sun Mar 13 2022",
                amount: 700,
                email: "user@gmail.com",
                last4: "4242",
                transaction: "p"
            },
            status: "Pending",
            billing: {
                country: "BD",
                name: "Md. Fathe Karim",
                phone: "+88010000000",
                line1: "Madhabdi",
                city: "Narshingdi",
                postal_code: "1604",
                state: "Bandarban"
            }
        }]

这是我来自前端的 POST 请求:

   await fetch('https://guarded-ocean-73313.herokuapp.com/dashboard/orders', {
                method: 'POST',
                headers: {
                    'content-type': 'application/json'
                },
                body: JSON.stringify({
                    products: [...cart], paymentDetails: {
                        createdId: paymentIntent.created,
                        date,
                        amount: paymentIntent.amount,
                        email: emailRef.current?.value,
                        billing: paymentIntent.billing_details,
                        last4: paymentMethod.card.last4,
                        transaction: paymentIntent?.client_secret.slice('_secret')[0]
                    },
                    status: 'Pending',
                    billing: {
                        country: countryRef.current?.value,
                        name: nameRef.current?.value,
                        phone: phoneRef.current?.value,
                        line1: addressRef.current?.value,
                        city: cityRef.current?.value,
                        postal_code: zipRef.current?.value,
                        state: stateRef.current?.value,
                    }
                })
            })
                .then(res => res.json())

这是我的订单 API

 app.post('/dashboard/orders', async (req, res) => {
            const productDetail = req.body
            const result = await unityMartOrdersCollection.insertOne(productDetail)
            res.json(result)
        })

我的期望是这样的:

[
        {
            _id: "622d70a49bd88b1599026318",  // Vendor 1 Order
            products: [
                {
                    _id: "6223186e2278d4e502f5264a",
                    title: "Product number 1",
                    price: 600,
                    cartQuantity: 1,
                    vendor: {email: "vendor1@gmail.com"}
                }
            ],
            paymentDetails: {
                createdId: 1647145079,
                date: "Sun Mar 13 2022",
                amount: 600, // price redcuded because we divided the product
                email: "user@gmail.com",
                last4: "4242",
                transaction: "p"
            },
            status: "Pending",
            billing: {
                country: "BD",
                name: "Md. Fathe Karim",
                phone: "+88010000000",
                line1: "Madhabdi",
                city: "Narshingdi",
                postal_code: "1604",
                state: "Bandarban"
            }
        },
     {
            _id: "622d70a49bd88b1599026319", // Vendor 2 Order
            products: [

                {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "vendor2@gmail.com"
                    }
                },
                 {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "vendor2@gmail.com"
                    }
                },
            ],
            paymentDetails: {
                createdId: 1647145079,
                date: "Sun Mar 13 2022",
                amount: 200, // price redcuded because we divided the product
                email: "user@gmail.com",
                last4: "4242",
                transaction: "p"
            },
            status: "Pending",
            billing: {
                country: "BD",
                name: "Md. Fathe Karim",
                phone: "+88010000000",
                line1: "Madhabdi",
                city: "Narshingdi",
                postal_code: "1604",
                state: "Bandarban"
            }
        }
]

我认为可以通过reduce 方法实现?

有人可以告诉我如何将供应商的订单显示到他们的仪表板中吗?如果我的想法是错误的,你可以分享你的想法。

【问题讨论】:

    标签: javascript node.js arrays reactjs


    【解决方案1】:

    这可能是实现预期目标的一种可能解决方案:

    代码片段

    const groupByVendor = arr => (
      arr.map(order => (
        Object.values( // sub-objective 1 - get values from object
          order.products.reduce(
            (fin, p) => ({
              ...fin,
              ...(
                [p.vendor.email] in fin
                ? {
                  [p.vendor.email]: {
                    ...fin[p.vendor.email],
                    products: fin[p.vendor.email].products.concat([{...p}]),
                    paymentDetails: {
                      ...structuredClone(fin[p.vendor.email].paymentDetails),
                      amount: fin[p.vendor.email].paymentDetails.amount + p.price
                    } // sub-objective 2 - add price to existing amount
                  }
                }
                : {
                  [p.vendor.email]: {
                    ...structuredClone(order), // sub-objective 3 - add order info here
                    paymentDetails: {
                      ...structuredClone(order.paymentDetails),
                      amount: p.price // sub-objective 2 - set amount to price
                    },
                    products: [{...p}]
                  }
                }
              )
            }),
            {}
          )
        )
      )).flat()
    );
    
    const rawData = [{
      _id: "622d70a49bd88b1599026318",
      products: [{
          _id: "6223186e2278d4e502f5264a",
          title: "Product number 1",
          price: 600,
          cartQuantity: 1,
          vendor: {
            email: "vendor1@gmail.com"
          }
        },
        {
          _id: "622d4e9f9bd88b1599026317",
          title: "asdas",
          price: 100,
          cartQuantity: 5,
          vendor: {
            email: "vendor2@gmail.com"
          }
        },
        {
          _id: "622d4e9f9bd88b1599026317",
          title: "asdas",
          price: 100,
          cartQuantity: 5,
          vendor: {
            email: "vendor2@gmail.com"
          }
        },
      ],
      paymentDetails: {
        createdId: 1647145079,
        date: "Sun Mar 13 2022",
        amount: 700,
        email: "user@gmail.com",
        last4: "4242",
        transaction: "p"
      },
      status: "Pending",
      billing: {
        country: "BD",
        name: "Md. Fathe Karim",
        phone: "+88010000000",
        line1: "Madhabdi",
        city: "Narshingdi",
        postal_code: "1604",
        state: "Bandarban"
      }
    }];
    
    console.log(groupByVendor(rawData));

    说明

    我们的想法是将期望的目标分解为更简单、更易于管理的子目标。

    子目标 1:用订单映射供应商的字典

    • 首先,使用 vendor 电子邮件生成一个带有 props 的对象。
    • 这些值将是与供应商对应的实际订单
    • 创建此对象后,我们只需要值数组

    子目标 2:更新paymentDetailss amount 的机制

    • 如果处理一个不存在的供应商,请将amount 设置为price
    • 如果供应商已经存在,请将price 添加到现有的amount

    子目标3:变换对象的结构

    • 目标要求数组中的每个对象都有paymentDetailsbilling等。
    • 因此,在为供应商对象/字典/地图生成值时,请考虑相应的转换

    代码-sn-p中标注了子目标以供参考。

    请使用 cmets 提出任何问题、澄清或提出改进建议。

    注意

    1. 此答案使用structuredClone 来执行order 对象的深度克隆。
    2. 我的参考是Jeremythis answer 以及this one

    【讨论】:

    【解决方案2】:

    在不使用结构化克隆的情况下修改以上仅拆分产品的答案,希望这可能会有所帮助

    const groupByVendor = arr => (
        arr.map(order => (
          Object.values( // sub-objective 1 - get values from object
            order.products.reduce(
              (previousProduct, product) => ({
                ...previousProduct,
                ...(
                  [product.owner] in previousProduct
                  ? {
                    [product.owner]: {
                      ...previousProduct[product.owner],
                      products: previousProduct[product.owner].products.concat([{...product}]),
                      // sub-objective 2 - add price to existing amount
                    }
                  }
                  : {
                    [product.owner]: {
                       // sub-objective 3 - add order info here
                     
                      products: [{...product}]
                    }
                  }
                )
              }),
              {}
            )
          )
        )).flat()
      );
      
      const rawData = [{
        _id: "622d70a49bd88b1599026318",
        products: [{
            _id: "6223186e2278d4e502f5264a",
            title: "Product number 1",
            price: 600,
            cartQuantity: 1,
            owner: "vendor1@gmail.com"
    
          },
          {
            _id: "622d4e9f9bd88b1599026317",
            title: "asdas",
            price: 100,
            cartQuantity: 5,
            owner: "vendor2@gmail.com"
            
          },
          {
            _id: "622d4e9f9bd88b1599026317",
            title: "asdas",
            price: 100,
            cartQuantity: 5,
            owner: "vendor2@gmail.com"
            
          },
        ]
      }];
      
      console.log(JSON.stringify(groupByVendor(rawData)));

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多