Pawan
Pawan

Reputation: 32321

How to create a nested array JSON?

This is the response I am getting when clicking on a confirm order button

<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>

Right now I am able to read the label text from the response and form a JSON array, as shown:

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

Using this:

var divdata = {
data: []
};

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

});

But I was also supposed to include a the tag's href value, that has the class tpActive, from the above response.

So that it looks as:

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

I was able to read the class tpActive via:

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

but I couldn't proceed as I don't know how to create an array inside of an array.

Can anyone help me to make a multi-dimensional array, please?

Upvotes: 0

Views: 65

Answers (1)

caspian
caspian

Reputation: 1804

You have to initialize the toppings array and then set the object in the main array:

$(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
             }

}); 

Upvotes: 1

Related Questions