gpt4 book ai didi

javascript - 如何比较两个数组并通过完整迭代删除重复对象

转载 作者:行者123 更新时间:2023-11-28 12:15:52 25 4
gpt4 key购买 nike

我有两个对象数组,

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"}
];

当我尝试使用以下逻辑比较和迭代两个数组时,

for  (var  i  of selectedRows) {
for  (var  j  of deSelectedRows) {
if  ( i.id  ===  j.id ) {
selectedRows.splice(i,  1);
}
}
}

由于正在拼接所选行,因此我无法完全迭代。请帮我解决这个问题。

最佳答案

您可以使用Set对于给定的 id 并使用该集合过滤 selectedRows

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);

关于javascript - 如何比较两个数组并通过完整迭代删除重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557351/

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