Search code examples
javascriptjqueryjsonbackbone.jsunderscore.js

Looping through JSON and spitting the contents into three columns


I have thousands of JSON objects in an array that I'm trying to display on the front-end in three columns. What is the best way to loop through all of these objects and display them in thirds? The objects are a just a list of names and css classes.

I'm using backbone.js and underscore.js, but I'm not sure what the best approach would be? I'm new to js and this is the first time I've really worked with JSON objects.

The code below is just appending to a ul with an id of "first." In the markup I have two other columns with the ids of "second" and "third".

            var colTotal = Math.ceil(view.usersCollection.length);

            view.usersCollection.each(function(user, i){
              var template = view.userTemplate(user.toJSON());
              $('#first').append(template);
            });

          <script type="javascript/template" id="user-template">
             <li class="<%= color %>"><%= name %></li>
          </script>

Solution

  • This should do the trick:

    var chunk = Math.ceil(myGreatBigArray.length / 3);
    
    var a1 = myGreatBigArray.slice(0, chunk);
    var a2 = myGreatBigArray.slice(chunk, chunk * 2 );
    var a3 = myGreatBigArray.slice(chunk * 2);
    

    If the array contains object references then slice will only copy the object references and not the whole object (ref slice).