Search code examples
javascriptjquerytablesorter

Create an array of object literals in a loop


I'm using a jQuery plugin to sort columns - tablesorter.

It lets you disable headers using options. At the moment I disable headers 2 & 3 by passing options when initialising the plugin:

$("#mytable").tablesorter({
  headers: {
    1: {  
      sorter: false 
    },
    2: { 
      sorter: false 
    }
  } 
});

I'd like to do it dynamically, by checking if a class "header" exists; if not I would disable the functionality.

Here is my jsfiddle

Any idea on how I could do it dynamically?


Solution

  • You can get all the theade th elements without the class header and then create a dynamic object like

    var headers = {};
    $('#mytable thead th').not('.header').each(function () {
        headers[$(this).index()] = {
            sorter: false
        };
    })
    
    console.log(headers)
    
    $("#mytable").tablesorter({
        headers: headers
    });
    

    Demo: Fiddle