Why doesn't the Javascript Set create unique objects?

Preferences should contain unique objects, but they do not 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 how deep a unique set is.

EDIT:

This is 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 sm.p

+4
source share
3 answers

This is naive, and I'm sure there are better ways to get unique data (for example, a database query returns unique data, but it will depend on the database), but you can check if the object is already in before installation.

var m = await(M.find({c: cID}).populate('p')) //database call
var p = new Set();
m.forEach(function(sm){
    if(!p.has(sm.p)) p.add(sm.p)
})
+3
source

, , , "Set", :

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);
};
+3

You can use Maps . If you need unique key-based values. For me, I wanted to have a unique selection from an array of object

let cats = [
    { category: 6 },
    { brand: 'purina' },
    { category: 5 },
    { category: 5 },
    { brand: 'purina' }];

var myMap = new Map();

cats.forEach(object => {
    for (const key in object) {
      myMap.set(key, object[key])
    }
})
console.log(myMap) //Map { 'category' => 5, 'brand' => 'purina' }

Here the category and brand are not repeated.

0
source

Source: https://habr.com/ru/post/1665382/


All Articles