我有两个对象数组。虽然 localDataArray
已存储在我的应用程序中,但 remoteUpdateDataArray
来自后端。
var localDataArray = [
{ "date": "10/01/19", "category": "surf", "hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709"},
{ "date": "10/01/19", "category": "skate", "hash": "a0f1490a20d0211c997b44bc357e1972deab8ae3"},
{ "date": "10/01/19", "category": "skate", "hash": "54fd1711209fb1c0781092374132c66e79e2241b"}
];
var remoteUpdateDataArray = [
{ "date": "12/01/19", "category": "surf", "hash": "4a0a19218e082a343a1b17e5333409af9d98f0f5"},
{ "date": "11/01/19", "category": "surf", "hash": "54fd1711209fb1c0781092374132c66e79e2241b"},
{ "date": "10/01/19", "category": "surf", "hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709"},
{ "date": "10/01/19", "category": "skate", "hash": "a0f1490a20d0211c997b44bc357e1972deab8ae3"},
{ "date": "10/01/19", "category": "skate", "hash": "54fd1711209fb1c0781092374132c66e79e2241b"}
];
我想从 remoteUpdateDataArray
中删除所有重复的对象。每个对象的唯一标识符是哈希值。
到目前为止,我有以下代码:
let hashValue = "54fd1711209fb1c0781092374132c66e79e2241b"
var filteredResult = remoteUpdateDataArray.filter(x => x.hash !== hashValue);
结果:
var filteredResult = [
{ "date": "12/01/19", "category": "surf", "hash": "4a0a19218e082a343a1b17e5333409af9d98f0f5"},
{ "date": "11/01/19", "category": "surf", "hash": "54fd1711209fb1c0781092374132c66e79e2241b"},
{ "date": "10/01/19", "category": "surf", "hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709"},
{ "date": "10/01/19", "category": "skate", "hash": "a0f1490a20d0211c997b44bc357e1972deab8ae3"}
];
如何设法删除数组内的其他对象(在本例中是两个重复的对象)?请记住,这些数组可能会变得相当大。
最佳答案
我将从您的第一个数组构建一个哈希列表(以保存迭代),然后简单地使用includes()进行过滤
const inLocalData = localDataArray.map(({hash: e}) => e);
const result = remoteUpdateDataArray.filter(({hash: e}) => ! inLocalData.includes(e));
console.log(result);
<script>
var localDataArray = [{
"date": "10/01/19",
"category": "surf",
"hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709"
},
{
"date": "10/01/19",
"category": "skate",
"hash": "a0f1490a20d0211c997b44bc357e1972deab8ae3"
},
{
"date": "10/01/19",
"category": "skate",
"hash": "54fd1711209fb1c0781092374132c66e79e2241b"
}
];
var remoteUpdateDataArray = [{
"date": "12/01/19",
"category": "surf",
"hash": "4a0a19218e082a343a1b17e5333409af9d98f0f5"
},
{
"date": "11/01/19",
"category": "surf",
"hash": "54fd1711209fb1c0781092374132c66e79e2241b"
},
{
"date": "10/01/19",
"category": "surf",
"hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709"
},
{
"date": "10/01/19",
"category": "skate",
"hash": "a0f1490a20d0211c997b44bc357e1972deab8ae3"
},
{
"date": "10/01/19",
"category": "skate",
"hash": "54fd1711209fb1c0781092374132c66e79e2241b"
}
];
</script>
关于javascript - 过滤具有多个值的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54196877/