繁体   English   中英

在嵌套数组中过滤数组的最佳方法

[英]Best way to filter array in nested array

我需要找到一种更好的方法来实现从更大的数组中提取数组并将该子数组过滤到一个新的子数组中,我想避免将 for 循环用于另一个 for 循环,我认为这可以用数组来完成map 或过滤器,但不知道如何异步使用它,这是我的代码:

/* This is how to response looks like */
const example_response = [
    {
        "customer_id": 77495325,
        "line_items": [
            {
                "external_inventory_policy": "decrement_obeying_policy",
                "grams": 0,
                "price": "49.00",
                "product_title": "Coffret Planète Noël Édition limitée",
                "properties": [],
                "quantity": 1,
                "shopify_product_id": 6646207021135,
                "shopify_variant_id": 39696573923407,
                "sku": "109P72AN23",
                "subscription_id": 203337080,
                "tax_lines": [
                    {
                        "price": "8.17",
                        "rate": "0.2",
                        "title": "FR TVA"
                    }
                ],
                "title": "Cvdvsdvde",
                "variant_title": ""
            }
        ],
        "note": "",
        "note_attributes": [],
        "processed_at": "2021-12-13T16:03:01",
        "scheduled_at": "2021-12-13T00:00:00",
        "type": "CHECKOUT",
        "updated_at": "2021-12-13T16:03:01"
    }
];
 
async function getOrdersList() {
  try {
    let url = `MY_URL`;
    
    let data = await fetch(url);
    let res =  await data.json();
    if(!res) throw new Error({'error':'no response'});
    
    let orders = res.orders;
    let lineItems = [];
    let lineItem = {};
    
    for (const [i, value] of orders.entries()) {
        let inlineItems = value.line_items;
        for (const [j, value2] of inlineItems.entries()) {
            lineItem['id'] = value2.shopify_product_id;
          lineItem['qty'] = value2.quantity;
          lineItems.push(lineItem)
        }
    }
    
    return lineItems;
  }
  catch(error) {
        console.error(error);
      } 
}

/* Output */
[{"id":6646207021135,"qty":2}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM