0

I am using Set, I am able to store unique primitive values in it, but I am not able to store unique objects in it based on their property values.

Here is my sample code :

"use strict"
var set = new Set();
var student1 = {
    "name":"abc",
    "id":1
}

var student2 = {
    "name":"xyz",
    "id":1
}
var student3 = {
    "name":"def",
    "id":3
}
set.add(student1);
set.add(student2);
set.add(student3);
console.log(set);

I want to add student object in set based on theier ID values i.e. two objects will be same if the values of their ID's are same.

imv_90
  • 145
  • 1
  • 2
  • 9
  • 1
    Perhaps you want a `Map` with id as key. –  Oct 13 '16 at 05:54
  • You can add the objects to an array first, inside that, checking duplicate `id` before adding to `Set`, Reference link: http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array – Tân Oct 13 '16 at 06:13

2 Answers2

0

It's probably better to use Map instead for your purposes.

const map = new Map()

const student1 = {
  "name":"abc",
  "id":1
}

const student2 = {
  "name":"xyz",
  "id":1
}
const student3 = {
  "name":"def",
  "id":3
}

map.set(student1.id, student1);
map.set(student2.id, student2);
map.set(student3.id, student3);

console.log(map);
uladzimir
  • 5,639
  • 6
  • 31
  • 50
0

The ES6 Set object uses value equality which pretty much means === checking (as ever with Javascript there is a bit nuance here though).

As others have suggested maybe what you really want is a Map by the id attribute.

Tom
  • 43,583
  • 4
  • 41
  • 61