Convert Table to an Array

后端 未结 5 1346
挽巷
挽巷 2020-12-14 04:43

I have seen many posts about how to turn an array into a table, but not nearly as many going the other way. I\'m looking to take a table like this:




        
5条回答
  •  悲&欢浪女
    2020-12-14 05:21

    So what I did is select all the tr elements and iterate over them. Next i check to make sure I am not looking at th elements. Then i use the cols array to populate the objects. This could have been simpler (2d array) but I use cols since that is what you had as your output.

    var i, items, item, dataItem, data = [];
    var cols = [ "category", "brandName", "whenObtained", "howObtained", "howOftenWorn",
     "whereMade", "hasGraphic" ];
    
    $("#dataTable tr").each(function() {
        items = $(this).children('td');
    
        if(items.length === 0) { // return if this tr only contains th
            return;
        }
    
        dataItem = {};
        for(i = 0; i < cols.length; i+=1) {
            item = items.eq(i);
            if(item) {
                dataItem[cols[i]] = item.html();
            }
        }
        data.push(dataItem);
    });
    

提交回复
热议问题