Create an array of objects by iterating through table rows

后端 未结 5 2032
鱼传尺愫
鱼传尺愫 2021-01-27 04:46

I have an HTML table and I want to iterate through its rows and create a collection or lets say an \"array of objects\".

For example:

5条回答
  •  误落风尘
    2021-01-27 05:02

    This solution relies on adding thead and tbody elements which is a good idea anyways since it indicates to the browser that the table actually is a "data" table and not presentational.

    jQuery has a .map() function. map is a basic function where you take an array and then replace the values with a the return value of a callback function - which results in a new array.

    $([1,4,9]).map(function(){ return Math.sqrt(this) });
    // [1, 2, 3]
    

    .toArray converts the array like jQuery object we get into a "true array".

    jQuery(function(){
      
      var $table = $("#tbPermission");
      
      var headers = $table.find('thead th').map(function(){
        return $(this).text().replace(' ', '');
      });
      
      var rows = $table.find('tbody tr').map(function(){
        var result = {};
        var values = $(this).find('>td').map(function(){
          return $(this).text();
        });
        // use the headers for keys and td values for values
        for (var i = 0; i < headers.length; i++) {
          result[headers[i]] = values[i];
        }
        
        // If you are using Underscore/Lodash you could replace this with
        // return _.object(headers, values);
    
        return result;
      }).toArray();
    
      
      // just for demo purposes
      $('#test').text(JSON.stringify(rows));
      
    });
    
    
    User ID User Name
    1 Test1

    If you for whatever reason cannot change the HTML you could use the index of the rows to differentiate between headers and rows of data:

      var headers = $table.find('tr:eq(0) th').map(function(){
        return $(this).text().replace(' ', '');
      });
    
      var rows = $table.find('tr:gt(0)').map(function(){
        // ...
      });
    

提交回复
热议问题