Search code examples
javascriptarrayshandsontable

Using arrays as columns with handsontable


I'm using handsontable to display data for an application. I want to use arrays as columns, which I can't seem to figure out with the documentation. I suppose the best approach would be to use an array of my arrays, but I'm having trouble piecing it together.

Here's the code so far:

var data = [
  ["Sale Month", "Usage", "Address", "Tax Assessment", "Loan Amount", "Initial Equity", "Lien Start Date", "Lien Term", "Loan Type", "Square Feet", "Year Build", "Acres"
      , "Beds", "Baths", "Lotsort"]
];

var container = document.getElementById('listview');
var hot = new Handsontable(container, {
  data: data,
  rowHeaders: true,
  colHeaders: true
});

I have a set of arrays for each column header. For example, the saleMonth array looks like ['01/18, 03/16, 01/12'] and so on. I want to use the indices of each array for entries in the corresponding column.

Here's the current output:

Screenshot

Please let me know if I can be more clear.

Thanks!

Edit: added a JSFiddle


Solution

  • I changed your data structure a little bit: changed data to a list of headers (columns) and moved your arrays of values into a map (values) where the key is the name of the column and the value is the original array

    In this way you could elaborate your data to create an array of rows in the suitable format

    var saleMonth = ['01/18', '03/20']
    var usageArray = ['Residential', 'Commercial']
    
    var values = {
      'Sale Month': saleMonth,
      'Usage': usageArray
    }
    
    var columns = 
      ["Sale Month", "Usage", "Address", "Tax Assessment", "Loan Amount", "Initial Equity", "Lien Start Date", "Lien Term", "Loan Type", "Square Feet", "Year Build", "Acres"      , "Beds", "Baths", "Lotsort"]
    
    ;
    
    var rows=[];
    var numOfRow
    for ( numOfRow = 0; numOfRow < saleMonth.length; numOfRow++ ) {
        rows.push(columns.map((e) => {
        if (e in values) {return values[e][numOfRow]}
        return e;
        }));
    }
    
    var container = document.getElementById('listview');
    var hot = new Handsontable(container, {
      data: rows,
      rowHeaders: true,
      colHeaders: true
    });
    

    You could also set in the Hansontable configuration object colHeaders: columns to get column titles instead of letters