簡體   English   中英

如何獲取嵌套 JSON 數組中的值

[英]How to get the values inside a nested JSON array

有人可以讓我知道如何訪問option_value數組中的值嗎? 它是另一個數組中的一個數組。

我的代碼出現以下錯誤:

類型錯誤:json.option[i].option_value[j] 未定義

我的代碼

$(document).on("click", "[name^='option']", function () {
  var value = $(this).val();
  var parent_id = $(this)
    .attr("name")
    .replace(/[^\d.]/g, "");

  $.ajax({
    url:
      "index.php?route=controlller/get_options&parent_id=" +
      parent_id +
      "&value=" +
      value +
      "&product_id=<?php echo $product_id; ?>",
    type: "get",
    dataType: "json",
    success: function (json) {
      if (json["option"]) {
        for (i = 0; i < json["option"].length; i++) {
          if (
            json["option"][i]["type"] == "radio" ||
            json["option"][i]["type"] == "checkbox"
          ) {
            $("#ioption" + json["option"][i]["product_option_id"])
              .find("input")
              .prop("checked", false);

            for (j = 0; j <= json["option"][i]["option_value"].length; j++) {
              $("#ioption" + json["option"][i]["product_option_id"])
                .find(
                  "input[value='" +
                    json["option"][i]["option_value"][j][
                      "product_option_value_id"
                    ] +
                    "']"
                )
                .parent()
                .show();
            }
          }
        }
      }
    },
    error: function (xhr, ajaxOptions, thrownError) {
      alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    },
  });
});

以下是我的 JSON 結果:

{
  "option": [
    {
      "product_option_id": "975",
      "option_id": "76",
      "name": "Stage",
      "type": "image",
      "option_value": [
        {
          "product_option_value_id": "2490",
          "option_value_id": "389",
          "name": "Level 1",
          "price": "\u20ac  2,00"
        },
        {
          "product_option_value_id": "2491",
          "option_value_id": "390",
          "name": "Level 2",
          "price": "\u20ac  3,00"
        }
      ],
      "required": "1"
    }
  ]
}

謝謝

我沒有你的 html 的確切結構,但至少我可以提供一個干凈的解決方案,使用一些Array.map用法。

你可以遍歷每個對象,然后你可以定位你想要的 HTML 元素。

例子

 result.option.map(opt => { if (opt.type === 'radio' || opt.type === 'checkbox') { let optionElement = '#ioption' + opt.option_id; $(optionElement).find('input').prop('checked', false); opt.option_value.map(optVal => { let inputElement = 'input[value=\\'' + optVal.product_option_value_id + '\\']'; $(optionIdElement).find(inputElement).parent().show(); }); } });

PS:代碼段不會運行,因為我沒有在答案中包含結果 json!

希望這會有所幫助!

獲取 option_value 的值使用這個option[0]["option_value"][0]我只是根據顯示頂部的 json 給出答案。 並且 0 根據您的要求使用任何循環(for / foreach)替換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM