我有一个从另一个供应商动态生成的CSV文件,我需要在我的站点上的一个表中显示。问题是,我需要能够操作CSV中的数据,这样它就可以在html表中显示校正的值。最后,我需要HTML表只显示产品,而不是混合集。
我使用jquery和papaparse库来获取数据,并在html中的一个表中解析它。我的书记员在这里
https://codepen.io/BIGREDBOOTS/pen/YQojww
javascript提取初始csv值并显示在表中,但我不知道如何将这些值相加。如果有更好的方法来实现这一点,比如将CSV转换为其他形式的数据(如JSON ),那也没关系。
我的CSV看起来是这样的:
product_title,product_sku,net_quantity
Product 1,PRD1,10
Product 2,PRD2,20
Product 3,PRD3,30
Mixed Set 1,MIX1,100
Mixed Set 2,MIX2,50
Mixed Set 3,MIX3,75我使用的Javascript是:
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [i] + '">'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
我的混合规则:
最后,我只想得到产品的输出,以及公式中添加的正确数字。最终结果将是一个表,其中Product1=185个,Product2=245个,Product3=155个。
虽然最好的头目元素是在一个“第四”,如果这是太复杂的罚款。
<table>
<tbody>
<tr class="rownum-0">
<td class="0">product_title</td>
<td class="0">product_sku</td>
<td class="0">net_quantity</td>
</tr>
<tr class="rownum-1">
<td class="1">Product 1</td>
<td class="1">PRD1</td>
<td class="1">185</td>
</tr>
<tr class="rownum-2">
<td class="2">Product 2</td>
<td class="2">PRD2</td>
<td class="2">245</td>
</tr>
<tr class="rownum-3">
<td class="3">Product 3</td>
<td class="3">PRD3</td>
<td class="3">155</td>
</tr>
</tbody>
</table>发布于 2017-07-19 18:13:03
在不知道您正在使用的数据集的大小的情况下,我建议您首先遍历所有CSV数据集,以填充具有正确值的产品列表,然后再对其进行迭代以填充HTML表:
function datasetToMap(data) {
var ret = {};
//Initialize a map with all the product rows
$(data).each(function(index, row) {
if(row[0].startsWith("Product")) {
ret[row[1]] = row; //Using the SKU as the key to the map
}
});
//Apply your mixed sets rules to the elements in the ret array
$(data).each(function(index, row) {
if(row[1] === "MIX1") {
ret["PRD1"][2] += 100;
ret["PRD2"][2] += 100;
}
//Do the same for Mixed sets 2 and 3
});
return ret;
}
function appendMapToTable(map) {
var $table = $('#my-table');
Object.keys(map).forEach(function(key, i) {
var rowData = map[key];
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [j] + '">'+cellData+'</td>'));
});
$table.append(row);
});
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
appendMapToTable(datasetToMap(Papa.parse(data).data));
}
});注意,这需要一个id my-table的表已经出现在您的HTML中:您可以手动解析CSV数据的第一行以添加表标题。
还请注意,如果CSV数据集非常大,这肯定不是一个最佳解决方案,因为它需要迭代所有行两次,然后再迭代所有用计算值构建的列表。
https://stackoverflow.com/questions/45197597
复制相似问题