【问题标题】:Best way to check each productId in order and if there is same productId add there quantity?按顺序检查每个产品 ID 的最佳方法以及是否有相同的产品 ID 添加数量?
【发布时间】:2021-03-17 20:15:45
【问题描述】:

我需要一个最佳解决方案来遍历每个订单项目,如果有两个产品 ID 匹配,则添加数量:

 var order = [
{
    "coupon": {},
    "billingAddress": {},
    "shippingAddress": {},
    "_id": "1234567890s4s5s3",
    "userId": 125,
    "subtotal": 15208,
    "shipping": null,
    "tax": 192,
    "total": 7700,
    "status": "confirmed",
    "orderItems": [
        {
            "productId": "5f44eb9a491a455bc6de2de5",
            "productTitle": "iPhone",
            "quantity": 1,
            "price": 3104,
            "tax": 96,
            "subtotal": 3104
        },
        {
            "productId": "5f44eb9a491a455bc6de2de5",
            "productTitle": "Iphone",
            "quantity": 1,
            "price": 3104,
            "tax": 96,
            "subtotal": 3104
        },
        {
            "productId": "5fc0b9646ce7332838122784",
            "productTitle": "Tv",
            "quantity": 1,
            "price": 4500,
            "subtotal": 4500,
            "tax": 0
        },
        {
            "productId": "5fc0b9646ce7332838122784",
            "productTitle": "Tv",
            "quantity": 1,
            "price": 4500,
            "subtotal": 4500,
            "tax": 0
        }
    ],

    "shipmentTracking": [
        {}
    ],
    "siteId": "5f3799e12c6291446ea8c75f",
},
{
    "billingAddress": {},
    "shippingAddress": {},
    "_id": "5f9d5bead92083a9810d526c",
    "status": "confirmed",
    "userId": 125,
    "subtotal": 121.25,
    "shipping": 5,
    "total": 130,
    "orderItems": [
        {
            "productId": "5f44eb9a491a455bc6de2de5",
            "productTitle": "Iphone",
            "quantity": 1,
            "price": 121.25,
            "subtotal": 121.25,
            "shipping": 5,
            "tax": 3.75
        }
    ],
    "siteId": "5f3799e12c6291446ea8c75f",

}]

请在这种情况下查看上面的代码如何获得如下输出:

数据:[{ 产品编号:5fc0b9646ce7332838122784, 产品名称:电视, 总数量:2, totalSaleAmount:--

},{产品 2 详细信息 }]

【问题讨论】:

    标签: javascript node.js arrays object


    【解决方案1】:

    试试这个:

    将订单项提取到单独的数组中,计算总数量和总销售额。参考以下代码

    var order = [
      {
          "coupon": {},
          "billingAddress": {},
          "shippingAddress": {},
          "_id": "1234567890s4s5s3",
          "userId": 125,
          "subtotal": 15208,
          "shipping": null,
          "tax": 192,
          "total": 7700,
          "status": "confirmed",
          "orderItems": [
              {
                  "productId": "5f44eb9a491a455bc6de2de5",
                  "productTitle": "iPhone",
                  "quantity": 1,
                  "price": 3104,
                  "tax": 96,
                  "subtotal": 3104
              },
              {
                  "productId": "5f44eb9a491a455bc6de2de5",
                  "productTitle": "Iphone",
                  "quantity": 1,
                  "price": 3104,
                  "tax": 96,
                  "subtotal": 3104
              },
              {
                  "productId": "5fc0b9646ce7332838122784",
                  "productTitle": "Tv",
                  "quantity": 1,
                  "price": 4500,
                  "subtotal": 4500,
                  "tax": 0
              },
              {
                  "productId": "5fc0b9646ce7332838122784",
                  "productTitle": "Tv",
                  "quantity": 1,
                  "price": 4500,
                  "subtotal": 4500,
                  "tax": 0
              }
          ],
      
          "shipmentTracking": [
              {}
          ],
          "siteId": "5f3799e12c6291446ea8c75f",
      },
      {
          "billingAddress": {},
          "shippingAddress": {},
          "_id": "5f9d5bead92083a9810d526c",
          "status": "confirmed",
          "userId": 125,
          "subtotal": 121.25,
          "shipping": 5,
          "total": 130,
          "orderItems": [
              {
                  "productId": "5f44eb9a491a455bc6de2de5",
                  "productTitle": "Iphone",
                  "quantity": 1,
                  "price": 121.25,
                  "subtotal": 121.25,
                  "shipping": 5,
                  "tax": 3.75
              }
          ],
          "siteId": "5f3799e12c6291446ea8c75f",
      
      }]
    
        //reducer function to be used to eztract order items
        const reducer = (accumulator=[],currentValue) => {
          if(currentValue.orderItems && currentValue.orderItems.length > 0){
            const extractedItems = currentValue.orderItems.map(item => {
              return {quantity:item.quantity ,productTitle:item.productTitle, price:item.price , productId:item.productId}
            })
      
            return accumulator.concat(extractedItems)
          }
        }
    
      //extracting order items
      const orederItems = order.reduce(reducer , [])
    
    
      
     // data which stores product ids as keys
      const data = {};
    
      //loop over extracted order items and populate data with totalSaleAmt and totalQty
      orederItems.forEach(item => {
        
        const currentQty = data[item.productId] && data[item.productId]["totalQty"] ? data[item.productId]["totalQty"]:0;
        const currentTotalSaleAmt = data[item.productId] && data[item.productId]["totalSaleAmt"] ? data[item.productId]["totalSaleAmt"]:0;
        data[item.productId] = {
          
          title:item.productTitle,
          totalQty:currentQty + item.quantity,
          totalSaleAmt:currentTotalSaleAmt + item.price
        }
        
      });
    
      //data will hold the required information
      console.log(data)
     
      

    【讨论】:

    • 嗨@DeepakTomson 可以使输出像数组一样吗?示例:[ {“productId”:“5f44eb9a491a455bc6de2de5”,“title”:“2L MagicPot Neo”,“totalQuantity”:“2L MagicPot Neo”,“totalSaleAmount”:6329.25},{“productId”:“5fc0b9646ce7332838122784”,“title ": "test", "totalQuantity": "test", "totalSaleAmount": 9000}]
    • //获取数据对象后在下面使用 // 转换为最终所需的数组 const finalData = Object.keys(data).map(dataItem => { return { ...data[dataItem] } } ) //finalData 会保存需要的信息 console.log(finalData)
    • 是的!@ DeepakTomson
    【解决方案2】:

    使用一个forEach 循环并跟踪同一产品的项目和增加数量。使用来自跟踪对象(结果)的Object.values

    const updateItems = (arr) => {
      const result = {};
      arr.forEach((item) => {
        result[item.productId] ??= { ...item, quantity: 0 };
        result[item.productId].quantity += 1;
      });
      return Object.values(result);
    };
    
    var order = [
      {
        orderId: "12345678912345gh",
        shippingAddress: {},
        billingAddress: {},
        orderItems: [
          {
            productId: "234567890qwe3456",
            productTitle: "iphone",
            quantity: 1,
            price: 40000,
          },
          {
            productId: "234567890qwe3116",
            productTitle: "pan",
            quantity: "1",
            price: 20000,
          },
          {
            productId: "234567890qwe3456",
            productTitle: "iphone",
            quantity: 1,
            price: 40000,
          },
          {
            productId: "234567890qwe3avc",
            productTitle: "vohone",
            quantity: 1,
            price: 40000,
          },
        ],
      },
    ];
    
    const output = order.map(({orderItems, ...item}) => ({
      ...item,
      orderItems: updateItems(orderItems),
    }));
    
    console.log(output)

    【讨论】:

      【解决方案3】:

      使用这个:

      for (let i = 0 ; i < order.length ; i++ ) {
          for (let j = i+1 ; j < order.length ; j++ ) {
              if (order[i].productId == order[j].productId)
                  // your code
          }
      }
      

      【讨论】:

      • 你可以在your code部分做任何你想做的事情。
      猜你喜欢
      • 2017-12-19
      • 2015-10-17
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多