首页 > 解决方案 > 过滤具有多个值的对象数组

问题描述

我有两个对象数组。虽然localDataArrayis 已经存储在我的应用程序中,但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"}
    ];

我如何设法摆脱数组中的另一个(在这种情况下是两个重复的对象)?请记住,这些数组可能会变得非常大。

标签: javascript

解决方案


我会从你的第一个数组中构建一个哈希列表(以保存迭代),然后简单地使用 include() 过滤

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>


推荐阅读