gpt4 book ai didi

javascript - 如何将逗号分隔值分解为

转载 作者:行者123 更新时间:2023-12-03 07:54:37 25 4
gpt4 key购买 nike

JSON

{
"catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"],
"price": ["100", "8"],
"qty": "",
"qty2": ["", ""],
"total_qty": "",
"total": "",
"mem": "10",
"email_2": "",
"ic_add": "890527-08-6136",
"comm": "20",
"grand": "",
"cash": "120",
"change": "120.00",
"cust_id": "TGF 566",
"cust_name": "coco crancy",
"mem_id": "123",
"mem_name": "QIZLAF MARKETING",
"action": "test"
}

上面的 json 通过 ajax 作为 jQuery 对象 传递到页面。我使用 foreach 循环来显示没有数组的值。对于那些具有数组值的人,我使用 $.each Loop 如下所示:

var _tableHTMl = "<table><thead><tr>"+
"<th>Item Name</th>"+
"<th>Unit Price RM</th>"+
"<th>Qty</th>"+
"<th>Amount</th></thead><tbody>";

$("#print_receipt").append(_tableHTML);


var new_array = {};

for (var i = 0; i < data.length; i++) {

new_array[i] = {
'catalog_name': data[i].catalog_name,
'price': data[i].price,
'qty': data[i].qty,
'amt': data[i].grand
};

}
//this simply displays all values within one `<tr>` with comma separated

$.each(new_array, function(index, value) {
$("#print_receipt").append(
"<table><tr><td>" +
value.catalog_name +
"</td><td>" +
value.price +
"</td><td>" +
value.qty +
"</td><td>" +
value.amt +
"</td></tr></tbody></table>"
);
});

输出:

enter image description here

Rajesh 建议的结果:
enter image description here

根据 BG101 建议的结果:

enter image description here

最佳答案

我已经对您的数据源应用了 split 函数,然后我只是将 json 对象提供给数据表(您仍然可以使用追加方法)。

$(document).ready(function() {

var json = '[{"catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"],"price": ["100", "8"],"qty": "","qty2": ["", ""],"total_qty": "","total": "","mem": "10","email_2": "","ic_add": "890527-08-6136","comm": "20","grand": "","cash": "120","change": "120.00","cust_id": "TGF 566","cust_name": "coco crancy","mem_id": "123","mem_name": "QIZLAF MARKETING","action": "test"}]';

var data = JSON.parse(json);

$.each(data,function(i,v){
if($.isArray(v.catalog_name)){
var newone = $.map(v.catalog_name,function(elem,j){
return {catalog_name: elem, price: v.price[j], qty: v.qty, grand: v.grand }
});
Array.prototype.splice.apply(data,[i, newone.length].concat(newone));
}
});

$('#table').DataTable({
data: data,
columns: [{
data: "catalog_name"
}, {
data: "price"
}, {
data: "qty"
}, {
data: "grand"
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>


<table id="table">
<thead>
<tr>
<th>Item Name</th>
<th>Unit Price RM</th>
<th>Qty</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

关于javascript - 如何将逗号分隔值分解为 <tr>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34850729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com