简体   繁体   English

es6具有设置的对象的唯一数组

[英]es6 unique array of objects with set

I came across this example for creating unique arrays with es6 我遇到了使用es6创建唯一数组的示例

[ ...new Set(array) ]

Which seems to work fine until I tried it with an array of objects and it didn't return unique array. 直到我尝试使用对象数组并且它没有返回唯一数组,这似乎都可以正常工作。

ie

let item = [ ...new Set([{id:123,value:'test'},{id:123,value:'test'}]) ];

Why is that ? 这是为什么 ?

Why is that ? 这是为什么 ?

As per documentation 根据文档

The Set object lets you store unique values of any type, whether primitive values or object references . Set对象使您可以存储任何类型的唯一值,无论是原始值还是对象引用

Now reference for each of those arrays inside that Set constructor will be different so they are not considered to be a unique value by the constructor. 现在,该Set构造函数中对每个数组的引用都将不同,因此构造函数不会将它们视为唯一值。

This will work: 这将起作用:

let objectReference = {id:123,value:'test'}
let uniqueArray = [...new Set([objectReference, objectReference])]

>> [{id:123,value:'test'}]

What you're doing: 你在做什么:

let objRef1 = {id:123,value:'test'} // creates a reference to a location in memory
let objRef2 = {id:123,value:'test'} // creates a new reference to a different place in memory

let uniqueArray = [...new Set([objRef1, objRef2])]

>> [{id:123,value:'test'},{id:123,value:'test'}]

you can try to do 你可以尝试做

uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s))

I know its ugly as hell but in most cases works apart from where you have new Date() in your object param then that on stringify be converted to ISO string. 我知道它很丑陋,但是在大多数情况下,除了在对象参数中有新Date()的地方起作用之外,然后在stringify上将其转换为ISO字符串。

so then do 所以做

let arr = [{id:1},{id:1},{id:2}];
uniqueArray(arr) //[{id:1},{id:2}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM