收集 JavaScript 数组中的唯一对象 [英] Collect unique objects in JavaScript array

查看:28
本文介绍了收集 JavaScript 数组中的唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下对象数组

var firstDataSet = [
  {'id': 123, 'name': 'ABC'},
  {'id': 456, 'name': 'DEF'},
  {'id': 789, 'name': 'GHI'},
  {'id': 101, 'name': 'JKL'}
];

var secondDataSet = [
  {'id': 123, 'name': 'ABC', 'xProp': '1q'},
  {'id': 156, 'name': 'MNO', 'xProp': '2w'},
  {'id': 789, 'name': 'GHI', 'xProp': '3e'},
  {'id': 111, 'name': 'PQR', 'xProp': '4r'}
];

现在我想收集具有唯一对象的数组(匹配 idname)i.e.

Now I want to collect array with unique objects (matching id and name)i.e.

var firstDataSet = [
  {'id': 123, 'name': 'ABC', 'xProp': '1q'},
  {'id': 456, 'name': 'DEF'},
  {'id': 789, 'name': 'GHI', 'xProp': '3e'},
  {'id': 101, 'name': 'JKL'},
  {'id': 156, 'name': 'MNO', 'xProp': '2w'},
  {'id': 111, 'name': 'PQR', 'xProp': '4r'}
];

我可以用

Array.prototype.unshift.apply(firstDataSet , secondDataSet );

但不确定如何过滤掉重复项.有什么建议吗?

But not sure how I can filter out duplicates. Any suggestion?

我在两个不同数组上的对象不相同.至少基于属性的数量.

My object on two different array are not same. At least based on number of properties.

推荐答案

删除具有所有相同属性的重复项

这是最初的问题.

使用 Set:

Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用.

The Set object lets you store unique values of any type, whether primitive values or object references.

您也可以使用对象字面量.

You can also use object literals.

var list = [JSON.stringify({id: 123, 'name': 'ABC'}), JSON.stringify({id: 123, 'name': 'ABC'})]; 
var unique_list = new Set(list); // returns Set {"{'id': 123, 'name': 'ABC'}"}
var list = Array.from(unique_list); // converts back to an array, and you can unstringify the results accordingly.

有关将集合构造回数组的更多方法,您可以按照此处的说明进行操作.如果你不能使用 ES6(它定义了 Set),还有一个 polyfill 适用于较旧的浏览器.

For more ways to construct a set back to an array, you can follow instructions here. If you can't use ES6 (which is what defines Set), there's a polyfill for older browsers.

不幸的是,这些对象不再是严格重复的,并且无法使用例如 Set 以友好的方式处理.

Unfortunately, these objects are no longer strictly duplicates and cannot be tackled in a friendly way using Set, for instance.

解决此类问题的最简单方法是遍历对象数组,识别具有重复属性值的对象,并使用例如 splice 就地消除.

The easiest way to approach this type of problem is to iterate through the array of objects, identify those with repeated property values, and eliminate in place using splice, for example.

这篇关于收集 JavaScript 数组中的唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆