嵌套For Loop Pass变量

时间:2016-11-09 16:21:50

标签: javascript loops for-loop foreach

我需要获得" site [id]"的预期价值。采取"购买[id]"。我使用对象键,因为数据变化,我不知道ID。实现这一目标的正确和最有效的方法是什么?

var data = {
  "user_id": null,
  "created_at": "2016-11-09T05:52:42.279Z",
  "total_prices": {
    "final_price": "$173.11",
    "shipping_price": "$13.18"
  },
  "notes": null,
  "used_profiles": null,
  "sites": {
    "56c6cce830bb1f28f8000022": {
      "info": {
        "url": "a1supplements.com",
        "name": "A1 Supplements",
        "logo": "https://px.twotap.com/unsafe/https%3A//core.twotap.com/system/sites/logos/56c6/cce8/30bb/1f28/f800/0022/small/56c6cce830bb1f28f8000022.png%3F1478498606243"
      },
      "prices": {
        "shipping_price": "$6.95",
        "final_price": "$86.90"
      },
      "details": {
        "shipping_estimate": "2-5 Days"
      },
      "order_id": "fake_confirm_order_id",
      "products": {
        "458aa2317f92043a0713b37e03b47b2d": {
          "original_url": "https://www.a1supplements.com/labrada-iso-leanpro",
          "clean_url": "https://www.a1supplements.com/labrada-iso-leanpro",
          "category_attributes": null,
          "categories": [
            "Everything Else"
          ],
          "status": "done",
          "required_fields": {
            "quantity": {
              "data": [{
                "input_type": "text",
                "input_name": "INPUT"
              }]
            },
            "flavor": {
              "data": [{
                "input_type": "select-one",
                "input_name": "SELECT"
              }]
            },
            "size": {
              "data": [{
                "input_type": "select-one",
                "input_name": "SELECT"
              }]
            }
          },
          "discounted_price": null,
          "pickup_support": false,
          "url": "https://www.a1supplements.com/labrada-iso-leanpro",
          "required_field_values": {
            "size": [{
              "weight": "2267.985122017599",
              "value": "5 Lbs.",
              "text": "5 Lbs.",
              "price": "$79.95",
              "image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
              "extra_info": "",
              "dep": {
                "flavor": [{
                  "weight": "2267.985122017599",
                  "value": "Chocolate",
                  "text": "Chocolate",
                  "price": "$79.95",
                  "image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
                  "extra_info": ""
                }, {
                  "weight": "2267.985122017599",
                  "value": "Vanilla",
                  "text": "Vanilla",
                  "price": "$79.95",
                  "image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
                  "extra_info": ""
                }]
              }
            }]
          },
          "required_field_names": [
            "size",
            "flavor",
            "quantity"
          ],
          "weight": "2267.985122017599",
          "site_categories": [
            "Home",
            "Protein",
            "Whey Protein Powder",
            "Whey Protein Isolate"
          ],
          "description": "100% Premium Whey Protein Isolate!\n<strong>Made with 100% PURE WHEY PROTEIN ISOLATE</strong> as the sole protein source, ISO LeanPro contains ZERO carbs, sugar, lactose and gluten&#x2014;no junk, fillers, or cheap blends.<br><br><strong>ISO LeanPro is not a blend</strong> containing whey protein concentrate, peptides, or other proteins. You get only 100% pure whey protein isolate as the source of protein.<br><br><strong>ISO LeanPro is sugar-free,</strong> and carb-free, so it&apos;s perfect for dieting.<br><br><strong>ISO LeanPro is lactose-free,</strong> so there is no bloating, gas, or indigestion associated with cheap proteins.<br><br><strong>ISO LeanPro is gluten-free,</strong> perfect for individuals who must avoid gluten because they suffer from gluten sensitivities.<br><br><strong>ISO LeanPro is perfect for athletes,</strong> bodybuilders, and fitness enthusiasts who demand the purest, highest quality protein available on the market.<br><br><strong>ISO LeanPro has a BV of 159,</strong> making it more bio-available than any other protein source. The most accurate way of testing the bioavailability of proteins is with the BV (Biological Value) method which measures actual nitrogen retention in humans.<br><br><strong>ISO LeanPro 100% Whey Protein Isolate</strong> is an excellent source of all the essential amino acids and is extremely rich in the branched chain amino acids (BCAAs), leucine, isoleucine, and valine.<br><br><strong>Branched chain amino acids</strong> make up one-third of muscle protein and are important to athletes because training increases the body&apos;s demand for them. An adequate supply of BCAAs in the blood is insurance against loss of muscle size and strength. ISO LeanPro is also high in glutamine, which accounts for approximately 60% of all free amino acids in the body.<br><br><strong>Labrada Nutrition CEO and IFBB Pro Bodybuilding</strong> Hall of Famer Lee Labrada says, &quot;ISO LeanPro is a very pure protein powder designed for elite athletes and bodybuilders who want the very best money can buy. ISO LeanPro is very quickly absorbed and utilized, so it&apos;s perfect for use right before and after training, to put the body into an anabolic state.&quot;<br><br> <strong>FDA</strong>: These statements have not been evaluated by the Food and Drug Administration. This product is not intended to diagnose, treat, cure, or prevent any disease.<br><br><i>Shop our 100% secure server and get your supplements at the lowest prices everyday! NOBODY beats our overall price.</i><br> <div> <h3>Supplement Facts</h3> <strong>Supplement Facts:</strong><br><br>Serving Size: 1 Scoop (32g)<br>Servings Per Container: 71<br><br>Amount Per Serving <br>Calories 115 <br>Calories from Fat 9 <br>Total Fat 1 g 2%<br>Saturated Fat 0 g 0%<br>Trans Fat 0 g <br>Cholesterol 0 mg 0%<br>Sodium 150 mg 6%<br>Potassium 150 mg 5%<br>Total Carbohydrate 1 g 0%<br>Dietary Fiber 0 g 0%<br>Sugars 0 g <br>Protein 25 g 50%<br>Vitamin A 0%<br>Vitamin C 0%<br>Calcium 13%<br>Iron 0%<br><br>Ingredients: Cross-Flow Micro Ultrafiltered Whey Protein Isolate, Natural &amp; Artificial Flavors, Dutched Cocoa, Cellulose Gum, Salt, Acesulfame Potassium, Sucralose.<br><br>NOTE: Supplement facts and ingredients may vary by flavor.<br><br>Allergen Information: Contains Milk, Soy.<br><br> </div> <div> <h3>Directions</h3> <p>Directions: Glass &#x2013; Fill glass with 4&#x2013;6 oz. of water or your favorite beverage. Add 1 scoop of ISO LeanPro, and mix with a spoon. Shaker &#x2013; Fill shaker with 4&#x2013;6 oz. of water or your favorite beverage. Add 1 scoop of ISO LeanPro. Cover and shake. Blender &#x2013; Fill blender with 4&#x2013;6 oz. of water or your favorite beverage. For a creamy ice cream flavor, add a handful of ice cubes. Add 1 scoop of ISO LeanPro. Cover and blend.<br><br>Note: Manufacturers continually change product specifications. While we try our best to keep product descriptions up to date, they do not necessarily reflect the latest information available from the manufacturer. We are not responsible for incorrect or outdated product descriptions and/or images. <br> <br></p> </div>",
          "image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
          "original_price": "$129.99",
          "price": "$79.95",
          "title": "Labrada ISO LeanPro",
          "input_fields": {
            "quantity": "1",
            "flavor": "Vanilla",
            "size": "5 Lbs."
          }
        }
      },
      "status": "done"
    },
    "5679041130bb1f37570026f5": {
      "info": {
        "url": "bodybuilding.com",
        "name": "Bodybuilding",
        "logo": "https://px.twotap.com/unsafe/https%3A//core.twotap.com/system/sites/logos/5679/0411/30bb/1f37/5700/26f5/small/5679041130bb1f37570026f5.png%3F1478589601755"
      },
      "prices": {
        "final_price": "$86.21",
        "shipping_price": "$6.23"
      },
      "details": {},
      "failed_to_add_to_cart": null,
      "order_id": "fake_confirm_order_id",
      "products": {
        "b634b0cc8751b14b54031c5c94d47de4": {
          "original_url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
          "clean_url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
          "weight": "1000",
          "category_attributes": null,
          "categories": [
            "Everything Else"
          ],
          "status": "done",
          "required_fields": {
            "option 1": {
              "data": [{
                "input_type": "select-one",
                "input_name": "SELECT"
              }]
            }
          },
          "discounted_price": null,
          "original_price": null,
          "pickup_support": false,
          "url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
          "required_field_values": {
            "option 1": [{
              "weight": "",
              "value": "56 Capsules",
              "text": "56 Capsules",
              "price": "$24.99",
              "image": "https://store.bbcomcdn.com/images/store/skuimage/sku_ZL008/image_skuZL008_largeImage_X_70_white.jpg",
              "extra_info": "clearance, clearance"
            }]
          },
          "required_field_names": [
            "option 1"
          ],
          "extra_info": "clearance clearance",
          "site_categories": [
            "Zantrex-3 Fat Burner"
          ],
          "description": "Famous High-Energy Component!*\nHigh Energy Fat Burning Support!*",
          "image": "https://store.bbcomcdn.com/images/store/prodimage/prod_35283/image_35283_original_X_450_white.jpg",
          "price": "$24.99",
          "title": "Zantrex-3 Fat Burner",
          "input_fields": {
            "quantity": "1",
            "option 1": "56 Capsules"
          }
        },
        "ba621a59cac993a24789d390efb741fc": {
          "title": "Hydroxycut CLA Elite Next Gen",
          "price": "$54.99",
          "image": "https://store.bbcomcdn.com/images/store/prodimage/prod_prod3990044/image_prodprod3990044_largeImage_X_450_white.jpg",
          "description": "Advanced, Scientifically-Tested Weight Loss Driver*\nSupplies 95% Cla Plus L-Carnitine And Garcinia Indica",
          "site_categories": [
            "Hydroxycut CLA Elite Next Gen"
          ],
          "extra_info": "Buy 1 Get 1 Free Buy 1 Get 1 Free",
          "required_field_names": [
            "option 1"
          ],
          "required_field_values": {
            "option 1": [{
              "extra_info": "Buy 1 Get 1 Free, Buy 1 Get 1 Free",
              "image": "https://store.bbcomcdn.com/images/store/skuimage/sku_MT4240203/image_skuMT4240203_largeImage_X_70_white.jpg",
              "price": "$54.99",
              "text": "100 Raspberry Flavored Softgels",
              "value": "100 Raspberry Flavored Softgels",
              "weight": ""
            }]
          },
          "url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
          "pickup_support": false,
          "original_price": null,
          "discounted_price": null,
          "required_fields": {
            "option 1": {
              "data": [{
                "input_name": "SELECT",
                "input_type": "select-one"
              }]
            }
          },
          "status": "done",
          "categories": [
            "Everything Else"
          ],
          "category_attributes": null,
          "weight": "1000",
          "clean_url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
          "original_url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
          "input_fields": {
            "quantity": "1",
            "option 1": "100 Raspberry Flavored Softgels"
          }
        }
      },
      "status": "done"
    }
  },
  "message": "done",
  "final_message": "Hi! We've confirmed 2 orders:\n\nA1 Supplements total $86.90 vs our initial estimate of $85.90 (shipping $6.95 vs estimated $5.95).\n* products: Labrada ISO LeanPro.\n* delivery estimate: 2-5 Days.\n* store order number: fake_confirm_order_id.\n\nBodybuilding total $86.21 vs our initial estimate of $91.41.\n* products: Zantrex-3 Fat Burner; Hydroxycut CLA Elite Next Gen.\n* delivery estimate: 2-5 Days.\n* store order number: fake_confirm_order_id.\n\nTotal $173.11."
};



var initial_index = Object.keys(data.sites)[0];
var product_index = Object.keys(data.sites[initial_index].products)[0];



var jj = (data.sites);

for (var key in jj) {
  if (jj.hasOwnProperty(key)) {

    console.log(key + ": " + jj[key]);

    var ee = (data.sites[jj].products);

    for (var key in ee) {
      if (ee.hasOwnProperty(key)) {

        console.log(key + ": " + ee[key]);

      }
    }
  }
}

执行上面的代码时,我收到以下错误,因为第一个循环中的变量没有传递给第二个循环。

VM1172:301 Uncaught TypeError: Cannot read property 'products' of undefined(…)

1 个答案:

答案 0 :(得分:0)

一些事情:

  • var ee = (data.sites[jj].products);无效,因为jj是对象,而不是密钥
  • 您已经声明key两次,因此内部循环将无法读取外部循环,因为它们具有相同的名称。
  • 只要您不需要旧版浏览器支持,通常最好在这些类型的循环中使用Object.keys(...).forEach(...)。 forEach调用的参数将是一个函数,该函数将在对象中的每个键上执行一次。更多信息here