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'}
]
逻辑是这样的:
- 目标关键字是"动物"
- 如果该字段没有其他元素具有相同的值,则保留它.
- 如果该字段有相同值的重复元素,但它是第一个,则保留它.
- 如果该字段存在具有相同值的重复元素,并且它不是第一个元素,则将其删除.
因此,该数组应为:
const result = [
{ checkID: 'aaa', animal: 'cat'},
{ checkID: 'bbb', animal: 'dog'},
{ checkID: 'ccc', animal: 'monkey'},
{ checkID: 'ddd', animal: 'horse'},
{ checkID: 'eee', animal: 'cow'}
]
这些元素是独一无二的,这使得工作变得复杂.我试着创建一个单独的数组,里面有动物的值,然后使用Filter方法,但是代码变得杂乱无章,并且认为可能有更好的方法.
有什么建议吗?谢谢