【问题标题】:Get object value based on conditions within nested array objects根据嵌套数组对象中的条件获取对象值
【发布时间】:2021-08-12 11:01:35
【问题描述】:

我有一个名为 orders 的对象数组:

    const orders = [
    {
        "order_id": 47445,
        "order_type": "Wholesale",
        "items": [
            {
                "id": 9,
                "department": "Womens",
                "type": "Dress",
                "quantity": 4,
                "detail": {
                    "ID": 13363,
                    "On Sale": 1,
                }
            }
        ]
    }
];

order_type(批发)和items.detail.ID(13363)匹配时,我需要获取数量。

到目前为止,我已经尝试了以下方法:

const result = orders.find(item => item.order_type == "Wholesale").items
  .reduce((total, item) => {
    if(item.detail.ID == 13363) {
      return item.quantity;
    }
  }, 0);

result 正确返回 4 的位置

我的问题,我确信我错过了一些非常简单的事情,那就是当我的 orders 数组中有多个 items 时,它会失败。

 const orders = [
    {
        "order_id": 47445,
        "order_type": "Wholesale",
        "items": [
            {
                "id": 9,
                "department": "Womens",
                "type": "Dress",
                "quantity": 4,
                "detail": {
                    "ID": 13363,
                    "On Sale": 1,
                }
            },
            {
                "id": 56,
                "department": "Womens",
                "type": "Skirt",
                "quantity": 12,
                "detail": {
                    "ID": 76884,
                    "On Sale": 0,
                }
            },
            {
                "id": 89,
                "department": "Mens",
                "type": "Shirts",
                "quantity": 20,
                "detail": {
                    "ID": 98223,
                    "On Sale": 1,
                }
            }
        ]
    }
];

一样

const result = orders.find(item => item.order_type == "Wholesale").items
  .reduce((total, item) => {
    if(item.detail.ID == 13363) {
      return item.quantity;
    }
  }, 0);

返回undefined

谢谢

【问题讨论】:

  • 只能有 1 个“批发”对象,其中一个 item.detail.ID 等于 13363?或者可以有多个(您想将所有匹配的数量相加吗?)
  • 正是您的最后一条评论,谢谢尼克。它需要允许多个并获得所有匹配数量的总和

标签: javascript arrays object nested array-filter


【解决方案1】:

find 助手只返回第一个匹配项,因此您需要使用另一个助手,例如 filter,如下所示:

const ID = 13363;

const result = orders
  .filter((order) => order.order_type === 'Wholesale')
  .reduce((acc, curr) => {
    const items = curr.items.filter((item) => item.detail.ID === ID);
    console.log(items);
    // You can sum the matching items and then push them into the acc array
    const quantity = items.reduce((sum, item) => (sum += item.quantity), 0);
    acc.push(quantity);
    return acc;
  }, []);

这将返回一个匹配数量的数组。

【讨论】:

  • 谢谢,这很好用,除了在某些情况下,有多个订单的批发类型和项目详细信息 id 为(在本例中)13363。这可能吗?这样它就可以找到与 Wholseale 和 Id 13363 匹配的一个或所有数量的总和。作为 const item = curr.items.find((item)... 仅获得第一个匹配项?
  • 是的,如果可能的话,您应该更改过滤器的查找,然后对所有结果元素求和。我编辑了答案,让您对此有所了解。
  • 那是完美的。感谢您的详细回答和解释
【解决方案2】:

不确定用例,但你去吧

const result = orders.find(item => item.order_type == "Wholesale").items
  .reduce((total, item) => {
    if (item.detail.ID == 13363) {
      total += item.quantity;
    }
    return total
  }, 0);

【讨论】:

    【解决方案3】:

    您甚至可以创建一个函数来使搜索动态化。

    const orders = [
    {
        "order_id": 47445,
        "order_type": "Wholesale",
        "items": [
            {
                "id": 9,
                "department": "Womens",
                "type": "Dress",
                "quantity": 4,
                "detail": {
                    "ID": 13363,
                    "On Sale": 1,
                }
            },
            {
                "id": 56,
                "department": "Womens",
                "type": "Skirt",
                "quantity": 12,
                "detail": {
                    "ID": 76884,
                    "On Sale": 0,
                }
            },
            {
                "id": 89,
                "department": "Mens",
                "type": "Shirts",
                "quantity": 20,
                "detail": {
                    "ID": 98223,
                    "On Sale": 1,
                }
            }
        ]
    }
    ];
    
    findMyItem=( ID )=>{
    var result  = null  ; 
    const result2 = orders.find(item => item.order_type == "Wholesale").items
      .map((  item) => {
        if(item.detail.ID == ID ) {
          result = item.quantity;
        }
      }, 0);
      return result ; 
      
    }
    
    
      
      
        
      console.log( "result" ,findMyItem(  13363 )   ) 
      console.log( "result" ,findMyItem(  98223)   ) 
      console.log( "result" ,findMyItem(  76884)   ) 

    【讨论】:

      【解决方案4】:

      您可以在 orders 数组上使用 Array.find() 来查找正确的订单,搜索与 order_type 匹配且项目与所需 itemId 匹配的第一个订单(使用 Array.some())。

      如果这个订单存在,我们可以再次使用.find()找到对应的商品数量,

      const orders = [ { "order_id": 47445, "order_type": "Wholesale", "items": [ { "id": 9, "department": "Womens", "type": "Dress", "quantity": 4, "detail": { "ID": 13363, "On Sale": 1, } }, { "id": 56, "department": "Womens", "type": "Skirt", "quantity": 12, "detail": { "ID": 76884, "On Sale": 0, } }, { "id": 89, "department": "Mens", "type": "Shirts", "quantity": 20, "detail": { "ID": 98223, "On Sale": 1, } } ] } ] 
      
      function findItemQuantity(orders, orderType, itemId) {
          // Find the first order with the right order_type and containing the right item id
          const order = orders.find(order => order.order_type = orderType && order.items.some(item => item.detail.ID === itemId));
          if (!order) { 
              return null;
          }
          const item = order.items.find(item => item.detail.ID === itemId);
          if (!item) { 
              return null;
          }
          return item.quantity;
      }
      
      console.log("Quantity found:", findItemQuantity(orders, 'Wholesale', 13363))
      console.log("Quantity found:", findItemQuantity(orders, 'Wholesale', 76884))
          

      【讨论】:

      • 为什么要引入null?
      • 如果我们找不到订单或商品,我们不知道对应的值。因此我们返回 null,也可以返回 undefined..
      • 好的,但是如果你想处理异常,你应该使用异常。
      • 我认为我不会认为找不到该项目是一个例外,对吧?很可能该项目根本不存在。
      【解决方案5】:
      const result = orders
        .filter(order => order.order_type == "Wholesale")
        .map(order => order.items.find(item => item.detail.ID == 13363))
        .filter(item => item)
        .reduce((total, { quantity }) => quantity + total, 0);
      

      【讨论】:

        【解决方案6】:

        const orders = [{
            "order_id": 47445,
            "order_type": "Wholesale",
            "items": [{
              "id": 9,
              "department": "Womens",
              "type": "Dress",
              "quantity": 4,
              "detail": {
                "ID": 13363,
                "On Sale": 1,
              }
            }]
          },
          {
            "order_id": 47445,
            "order_type": "Whole",
            "items": [{
              "id": 9,
              "department": "Womens",
              "type": "Dress",
              "quantity": 4,
              "detail": {
                "ID": 13363,
                "On Sale": 1,
              }
            }]
          }
        ]
        
        const result = orders.reduce(v => {
          return v.items.map(a => {
            if (v.order_type == 'Wholesale' && a.detail.ID == 13363) {
              return v
            }
          })
        })
        console.log(result)

        【讨论】:

          【解决方案7】:

          const orders = [{
            "order_id": 47445,
            "order_type": "Wholesale",
            "items": [{
              "id": 9,
              "department": "Womens",
              "type": "Dress",
              "quantity": 4,
              "detail": {
                "ID": 13363,
                "On Sale": 1,
              }
            }]
          }];
          
          var result = null;
          const result2 = orders.find(item => item.order_type == "Wholesale").items
            .map((item) => {
              if (item.detail.ID == 98223) {
                result = item.quantity;
              }
            }, 0);
          
          
          console.log("result", result)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-12-31
            • 2020-03-11
            • 1970-01-01
            • 2023-03-12
            • 2022-01-10
            • 1970-01-01
            • 2018-10-14
            • 2021-11-29
            相关资源
            最近更新 更多