Convert Sheetjs Object

JavaScript

console.clear();

// ========================================================================
// Converts the excel sheetjs "object of objects" to a useable format
// NOTE: a prototype using array.reduce
// 1. Converts the object to an array of keys
// 2. Sorts by row number
// 2. Filters out unneeded keys
// 3. Reduces the array into a 2d array grouping the rows
// 		and assigns the key value
// ========================================================================
function convertSheet(sheetObj) {
  
  var rowIndex = -1; // tracks the row we are on
  
  // Do Work: Covert to an array list
  var sheetList = Object.keys(sheetObj)
    .sort(sortSheet)
    .reduce(reduceSheet, []);

  // Return Work: Returning the proper format
  return {
    headers: sheetList.shift(),
    rowData: sheetList
  }
  
  // Sorts the sheetObj
  function sortSheet(a, b) {
    // sorting by row number
    // NOTE: assuming we are sorted by column already
    var order = getRowNumber(a) - getRowNumber(b);
    if (order < 0) {
      return -1;
    }
    if (order > 0) {
      return 1;
    }
    return 0;
  }
  
  // Reduces the sheetObj
  function reduceSheet(previousValue, currentValue, currentIndex, array) {
    if (currentValue == '!ref') {
      return previousValue;
    } else if (currentIndex === 0 || getRowNumber(currentValue) !== getRowNumber(array[currentIndex - 1])) {
      // Insert new row with value
      rowIndex++;
      return previousValue.concat([
        [sheetObj[currentValue]]
      ]);
    } else {
      // Add column to existing row with value
      previousValue[rowIndex].push(
        sheetObj[currentValue]
      )
      return previousValue;
    }
  }
  
  // Helper function that returns row number used for sorting
  function getRowNumber(str) {
    if (str.match(/[0-9]/g) === null) {
      return 0;
    }
    return Number(str.match(/[0-9]/g).toString().replace(/[,]/g, ''));
  }
}

// ========================================================================
//...