Search code examples
javascriptjsondetach

detach first json element and append to a different div?


json:

{
   "storeList":{
      "state":[
         {
            "stateName":"Maine",
            "store":[
               {
                  "storeName":"Store 1",
                  "storeID":"store1",
                  "storeURL":"http:\/\/www.sitename.com"
               },
               {
                  "storeName":"Store 2",
                  "storeID":"store2",
                  "storeURL":"http:\/\/www.sitename.com"
               },
               {
                  "storeName":"Store 3",
                  "storeID":"store3",
                  "storeURL":"http:\/\/www.sitename.com"
               }
            ]
         },
         {
            "stateName":"Connecticut",
            "store":[
               {
                  "storeName":"Store 1",
                  "storeID":"store1",
                  "storeURL":"http:\/\/www.sitename.com"
               }
            ]
         }
      ]
   }
}

and my function to render on page:

$(document).ready(function() {
                    var object;
                    $.getJSON('xml/storeList.json', function(json) {
                        object = json;
                        $('#storeList').append('<ul/>')
                        $.each(object.storeList.state, function() {
                        var list = $('#storeList ul'),
                            listItem = $('<li/>'),
                            html = listItem.append($('<h3/>').text(this.stateName));

                        $.each(this.store, function() {
                            listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
                        });

                        list.append(html)
                        });
                    });

                    });

I want to take the first "state" object and append it to a different div than the others. thanks! I realize the json is an array, but I'm unsure how the positioning works within json.


Solution

  • You can get the index of the current value directly from the $.each function.

    $.each(object.storeList.state, function(index, value) {
      var div;
      if(index == 0) {
        div = $('#firstItemDiv');
      } else {
        div = $('#otherItemsDiv');
      }
      div.append(...);
    });