1

I've a json array where I want to split it into 4 element sub arrays. I've written a loop to go through each element and create a dom element which I need to insert into the parent DOM element. but the function appends a set of parent elements whihc only contains one sub element to the document. Could any one help me on what wrong I'm doing.

jsonString.hotelDetails.forEach(function(elem){

    var hotel = hotelModel.clone();
    hotel.find('.location').html(elem.city);
    hotel.find('.name').html(elem.hotelName);
    hotel.find('.hotel-price').html(elem.currencyCode + " " + elem.adultRate);
    hotelArray.push(hotel);

    if(hotelArray.length == 4){
        $('<div/>', { class: 'search-result-row'}).append(hotelArray).append('<div class="clear"></div>').appendTo('.search-result-container');
        hotelArray = [];
    }else if( (dataLength % 4) == hotelArray.length){
        $('<div/>', { class: 'search-result-row'}).append(hotelArray).append('<div class="clear"></div>').appendTo('.search-result-container');
        hotelArray = [];
    }


});
Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
  • Giie us a fiddle of it please – Nicolas Henrard Jun 22 '14 at 11:06
  • Cannot create a fiddle cus the layout is large. – Imesh Chandrasiri Jun 22 '14 at 11:12
  • 1
    Haven't tested, but first of all, I would remove the `else if` condition outside the loop and after the loop put `if (hotelArray.length) ...`. Secondly, you cannot build a set of jQuery objects by appending jQuery objects to an array. Well you can, but functions like `append` will not work as expected. Try doing `hotelArray.push(hotel[0]);`. Finally, I wouldn't name `jsonString` a variable which contains an object, it's very misleading. – plalx Jun 22 '14 at 11:19
  • I've tried removing added elements and modifiying the original array but no change. – Imesh Chandrasiri Jun 22 '14 at 11:44

0 Answers0