如何在jQuery中使用嵌套的foreach循环?
我的数组看起来像这样如何在jQuery中使用嵌套的foreach循环?,jquery,Jquery,我的数组看起来像这样 productTable:Array(3) '[{ id:1 name:"Apple" today:10 yearly:21 }, { id:2 name:"Banana" today:14 yearly:45 }, { id:2 name:"Mangoes"
productTable:Array(3)
'[{
id:1
name:"Apple"
today:10
yearly:21
},
{
id:2
name:"Banana"
today:14
yearly:45
},
{
id:2
name:"Mangoes"
today:5
yearly:95
},
Period | Apple | Banana | Mangoes |
-------+--------+---------+---------+
Yearly | 21 | 45 | 95 |
Today | 10 | 14 | 5 |
我想把桌子做成这样
productTable:Array(3)
'[{
id:1
name:"Apple"
today:10
yearly:21
},
{
id:2
name:"Banana"
today:14
yearly:45
},
{
id:2
name:"Mangoes"
today:5
yearly:95
},
Period | Apple | Banana | Mangoes |
-------+--------+---------+---------+
Yearly | 21 | 45 | 95 |
Today | 10 | 14 | 5 |
我的html代码中,id=product title表示产品标题,id=product\u项表示上述数据
<table>
<tr id="product_title">
</tr>
<tbody>
<tr id="product_item">
</tr>
</tbody>
</table>
我的脚本文件是这样的;我从中得到了一个错误。所有数据都未定义
<script>
fetch('http://127.0.0.1:8000/api/productTable')
.then(response=>response.json())
.then(data=>{
$('#product_title').append("<th>Period</th>");
data.productTable.forEach(function (product) {
$('#product_title').append('<th>'+product.name +'</th>');
});
$.each(['yearly','today'],function (i,period) {
$('#product_item').append('<td>'+ period +'</td>');
$.each(data.retailsTable, function(result) {
$('#product_item').append('<td>'+ result.period +'</td>');
});
})
});
</script>
取('http://127.0.0.1:8000/api/productTable')
.then(response=>response.json())
。然后(数据=>{
$(“#产品名称”)。追加(“期间”);
data.productTable.forEach(函数(产品){
$(“#产品名称”)。附加(“”+product.name+“”);
});
$。每个(['每年','今天'],函数(i,周期){
$(“#产品项目”)。追加(“”+期间+“”);
$.each(data.statable,函数(result){
$(“#产品_项”)。追加(“”+result.period+“”);
});
})
});
首先,您需要周期的单独行,您可以使用简单循环创建这些行,并根据周期值为每一行指定一个id。如果愿意,这些行也可以硬编码到html中
然后将现有的周期循环移动到主数组的循环中,以便将名称添加到标题行,并将每个关联的周期值添加到周期行
对于变量属性名称,请使用[]
符号
[‘每年’、‘今天’].forEach(期间=>{
const id=period.toLowerCase();
const$row=$('',{id:id}).append($('',{text:period}));
$(“#产品_表”)。追加($row)
})
$(“#产品名称”)。追加(“期间”);
//循环数组中的每个项
data.forEach(产品=>{
//在标题行中插入名称
$(“#产品名称”)。附加(“”+product.name+“”);
//每个产品周期值的内部循环
[‘每年’、‘今天’].forEach(期间=>{
常量$row=$(“#”+期间);
$row.append(“”+产品[期间]+“”)
});
});代码>
常数数据=[{
id:1,
名称:“苹果”,
今天:10,,
年度:21
},
{
id:2,
名称:“香蕉”,
今天:14,,
年度:45
},
{
id:2,
名称:“芒果”,
今天:5,,
年:95
}
]
@marc\s谢谢你,如果我需要再添加两个类似这种类型的表和两个不同的数组?那么我想这会是个问题吗?像我这样创建两个表,然后每个产品周期的循环值将只出现在第一个表中?我该如何解决?这应该不是个问题,但代码需要更具体一点来隔离每个表。例如,不能使用相同的ID