避免迭代外循环



我有一个场景,我必须迭代两个列表或数组以获得所需的值。所以我要这样做:

var html = "";
$.each(list, function (i, set1) { //set1 is a list or array
$.each(set1.Tabs, function (i, set2) { //set1.Tabs is another one
html += "<li><a href='#" + set2.TabName + "'>" + set2.Details + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";                                   
})
})

上面的工作很好,它返回我需要的数据。但问题是,假设外部循环有10个值,内部循环有4个值。所以内循环用这四个值迭代了十次。这是很自然的,应该这样做。我试图使用以下方法获得不同的值(特别是对于外部循环):

list = list.filter((x, i, a) => a.indexOf(x) === i);

虽然上面应该可以工作,但我的预期输出如下:

输入>:(1、2、3、3、4、5、6,6]
输出: [1,2,3,4,5,6]

N。B我关心的是内部循环,而不是外部循环。但是为了迭代内循环,我必须先遍历外循环。有什么办法可以让内循环直接工作吗?

更新1示例代码

$(document).ready(function() {
var html = "";
var data = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" }
]
}
]
$.each(data, function(i, set1) { //set1 is a list or array
$.each(set1.topping, function(i, set2) { //set1.Tabs is another one
html += "<li><a href='#" + set2.id + "'>" + set2.type + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
})
})
$('#add').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add"></div>

您可以基于id创建唯一的浇头,然后使用唯一浇头呈现列表。要创建独特的浇头,您可以使用flatMap()Object.values()array#reduce

$(document).ready(function() {
var html = "";
var data = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
}
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
}
]
}
]
const uniqueToppings = Object.values(data
.flatMap(o => o.topping)
.reduce((r, {id, type}) => {
r[id] = r[id] || {id, type};
return r;
},{}));;
$.each(uniqueToppings, function(i, set) {
html += "<li><a href='#" + set.id + "'>" + set.type + "</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
});
$('#add').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="add"></div>

最新更新