如何创建嵌套数组JSON?

时间:2014-06-19 15:38:21

标签: jquery

这是我点击确认订单按钮时​​得到的回复

<div class="prd-items-detials">
   <form>
      <label for="checkbox-mini-0">Large, 100 Ml</label>
   </form>
</div>
<div class="Topping-details" id="61" style="display: none;">
   <section id="topping_tsection_61">
      <i id="topping-close"></i>
      <aside>
         <h6 class="tdHeading">Large, 100 Ml0</h6>
         <img src="images/arrow-topping.png">
         <section class="secclass"><a href="#" class="tpActive">Honey 10 ML</a></section>
         <section class="secclass"><a href="#">Honey with Carmel  10 ML</a></section>
      </aside>
      <aside>
         <h6 class="tdHeading">Large, 100 Ml1</h6>
         <img src="images/arrow-topping.png">
         <section class="secclass"><a href="#">Sauce  10 ML</a></section>
         <section class="secclass"><a href="#" class="tpActive">Honey with Carmel  10 ML</a></section>
      </aside>
   </section>
</div>
</div>
</div>
<div id="ordersdiv" style="display:none"></div>

现在我能够从响应中读取标签文本并形成一个JSON数组,如下所示:

[{"name":"Large, 100 Ml"] 

使用此:

var divdata = {
data: []
};

$(document).on("click", ".btn-confirmorder", function() {
            name = $(elem).find("label").text();
            if (name != 'undefined') {
                divdata.data.push({
                    "name": name
                 }

});

但我也应该在上面的回复中包含a标记的href值,该值包含类tpActive

所以它看起来像:

[
    {
        "name": "Large, 100 Ml",
        "toppings": [
            {
                "name": "Large, 100 Ml0",
                "value": "Honey 10 ML"
            },
            {
                "name": "Large, 100 Ml1",
                "value": "Honey with Carmel  10 ML"
            }
        ]
    }
]

我能够通过以下方式阅读课程tpActive

   toppings = $(elem).find(".tpActive").text();

但我无法继续,因为我不知道如何在数组内部创建数组。

有人可以帮我制作一个多维阵列吗?

1 个答案:

答案 0 :(得分:1)

您必须初始化toppings数组,然后在主数组中设置对象:

$(document).on("click", ".btn-confirmorder", function() {
        name = $(elem).find("label").text();
        if (name != 'undefined') {
            var toppings = [];
            var toppingText = $(elem).find(".tpActive").text();

            // not sure how your data is formated, so loop through that however...
            // for (...)
            toppings.push( { "name": "name-text", "value": "value-text" });

            divdata.data.push({
                "name": name,
                "toppings": toppings
             }

});