Note: This is not a duplicate question, as the elements are all unique. If the elements were the same I wouldn't have asked. I am talking about a single key values...

我正在try 找到一种有效的方法来从除了第一个这样的对象之外的唯一对象数组中删除具有重复键-值对的元素.即

假设我有一个对象数组,如下所示:

    const array = [
        { checkID: 'aaa', animal: 'cat'},
        { checkID: 'bbb', animal: 'dog'},
        { checkID: 'ccc', animal: 'monkey'},
        { checkID: 'ddd', animal: 'horse'},
        { checkID: 'eee', animal: 'cow'},
        { checkID: 'fff', animal: 'cat'}
    ]

逻辑是这样的:

  1. 目标关键字是"动物"
  2. 如果该字段没有其他元素具有相同的值,则保留它.
  3. 如果该字段有相同值的重复元素,但它是第一个,则保留它.
  4. 如果该字段存在具有相同值的重复元素,并且它不是第一个元素,则将其删除.

因此,该数组应为:

    const result = [
        { checkID: 'aaa', animal: 'cat'},
        { checkID: 'bbb', animal: 'dog'},
        { checkID: 'ccc', animal: 'monkey'},
        { checkID: 'ddd', animal: 'horse'},
        { checkID: 'eee', animal: 'cow'}
    ]

这些元素是独一无二的,这使得工作变得复杂.我试着创建一个单独的数组,里面有动物的值,然后使用Filter方法,但是代码变得杂乱无章,并且认为可能有更好的方法.

有什么建议吗?谢谢

推荐答案

你可以用想要的过滤密钥在闭包中取Set分.

const
    uniqueBy = (k, s = new Set) => o => !s.has(o[k]) && s.add(o[k]),
    array = [{ checkID: 'aaa', animal: 'cat' }, { checkID: 'bbb', animal: 'dog' }, { checkID: 'ccc', animal: 'monkey' }, { checkID: 'ddd', animal: 'horse' }, { checkID: 'eee', animal: 'cow' }, { checkID: 'fff', animal: 'cat' }],
    result = array.filter(uniqueBy('animal'));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Javascript相关问答推荐

我无法使用tailwind-css和reactJS修改图像的位置

在JS中转换mysql UTC时间字段?

如何在react-Router-dom 6中Forking 路由?

如何通过继承contentitable属性的元素捕捉keydown事件?

成帧器运动中的运动组件为何以收件箱开始?

拖放仅通过 Select 上传

使用复选框在d3.js多折线图中添加或删除线条

在服务器上放置了Create Reaction App Build之后的空白页面

如何将Cookie从服务器发送到用户浏览器

并不是所有的iframe都被更换

第二次更新文本输入字段后,Reaction崩溃

在使用位板时,如何在Java脚本中判断Connect 4板中中柱的对称性?

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

向数组中的对象添加键而不改变原始变量

如何防止ionic 输入中的特殊字符.?

如何为仅有数据可用的点显示X轴标签?

将范围 Select 器添加到HighChart面积图

通过跳过某些元素的对象进行映射

如何更改Html元素S的 colored颜色 ,然后将其褪色为原始 colored颜色

为什么NULL不能在构造函数的.Prototype中工作