我有一个数组,其中包含2个forEach循环,如下所示。
array1.forEach(o1 => unique_array2.forEach(o2 => {
if (o1.uName == o2.uName && o1.uid == o2.uid) {
//matches.push(o1);
break;
}
}));
如果找到匹配项,我想退出循环本身。我试图放置一个中断,但是它说非法的break语句自循环以来就存在。
我可以创建另一个假数组,然后将所有负值放置如下:
if (o1.uName == o2.uName && o1.uid == o2.uid) {
matches.push(o1);
}
else{
nonMatches.push(o1);
}
然后检查nonMatches数组,然后相应地返回。但是我试图避免这种情况,因为我的数组可能很大,一旦找到匹配项,我就想停止。
如果需要,这是我的摘录:
var array1 = [{
id: 0,
name: "adam",
uName: "aSilver",
uId: "123",
table: "table1"
},
{
id: 1,
name: "john",
uName: "jBerlin",
uId: "456",
table: "table1"
}
];
var array2 = [{
id: 0,
name: "adam",
uName: "aSilver, jBerlin",
uId: "123, 456",
createdBy: "auto",
createdOn: "09/10/2018",
desc: "none",
table: "table1"
},
{
id: 1,
name: "john",
uName: "aSilver, jBerlin",
uId: "123, 456",
createdBy: "auto",
createdOn: "09/10/2018",
desc: "none1",
table: "table1"
},
{
id: 0,
name: "steve",
uName: "aSilver, jBerlin, pParis",
uId: "123, 456, 789 ",
createdBy: "auto ",
createdOn: "09 / 10 / 2018 ",
desc: "none2",
table: "table2"
},
{
id: 0,
name: "nash",
uName: "aSilver, jBerlin, pParis",
uId: "123, 456, 789 ",
createdBy: "auto ",
createdOn: " 09 / 10 / 2018 ",
desc: "none3 ",
table: "table2"
},
{
id: 0,
name: "sand",
uName: "aSilver",
uId: "123",
createdBy: "auto",
createdOn: "09/10/2018",
desc: "none4",
table: "table3"
}
];
obj = {};
array2.forEach(o => obj[o.table] = o);
unique_array2 = Object.keys(obj).map(k => obj[k]);
matches = [];
array1.forEach(o1 => unique_array2.forEach(o2 => {
if (o1.uName == o2.uName && o1.uid == o2.uid) {
//matches.push(o1);
break;
}
}));
console.log(matches);
还有其他解决方法吗?