本文介绍了如何比较两个数组并通过完全迭代删除重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个对象数组,
var deSelectedRows = [
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}
];
var selectedRows = [
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}
];
当我尝试使用以下逻辑比较和迭代两个数组时,
And when I am trying to compare and iterate with two arrays with the below logic,
for (var i of selectedRows) {
for (var j of deSelectedRows) {
if ( i.id === j.id ) {
selectedRows.splice(i, 1);
}
}
}
由于已拼接选定的行,因此我无法完全进行迭代.请帮助我.
Since the selected rows are being spliced, I am not able to iterate completely.Please help me with this.
推荐答案
您可以使用,并使用该集合过滤selectedRows
.
You could use a Set
for the given id
and filter selectedRows
with the set.
var deSelectedRows = [{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}],
selectedRows = [{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}],
ids = new Set(deSelectedRows.map(({ id }) => id));
selectedRows = selectedRows.filter(({ id }) => !ids.has(id));
console.log(selectedRows);
这篇关于如何比较两个数组并通过完全迭代删除重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!