Sets are supposed to contain unique objects, but it doesn't work for objects in javascript.
var set = new Set() <- undefined set.add({name:'a', value: 'b'}) <- Set {Object {name: "a", value: "b"}} set.add({name:'a', value: 'b'}) <- Set {Object {name: "a", value: "b"}, Object {name: "a", value: "b"}}
It works for primitives
var b = new Set() <- undefined b.add(1) <- Set {1} b.add(2) <- Set {1, 2} b.add(1) <- Set {1, 2}
So how do I get it to work with objects? I get the fact that they are different objects with the same values, but I'm looking for like a deep unique set.
EDIT:
Here's what I'm actually doing
var m = await(M.find({c: cID}).populate('p')) //database call var p = new Set(); m.forEach(function(sm){ p.add(sm.p) })
This is to get a unique list of sm.p
Sets are supposed to contain unique objects, but it doesn't work for objects in javascript.
Set objects are collections of values. A value in the Set may only occur once; it is unique in the Set 's collection.
If you have an array of objects instead and need to find the unique values of one object property across all of those objects, you can do it with Set .
well, if you are looking for a deep unique set, you can make a deep set by youself, by extending the original 'Set', like this:
function DeepSet() { // } DeepSet.prototype = Object.create(Set.prototype); DeepSet.prototype.constructor = DeepSet; DeepSet.prototype.add = function(o) { for (let i of this) if (deepCompare(o, i)) throw "Already existed"; Set.prototype.add.call(this, o); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With