const mySet = new Set();
mySet.add(1);
mySet.add(1);
console.log(mySet); // Set { 1 }
// 結果
// {
// 0: 1
// }
const myCollection = new Set();
myCollection.add({id: 1, name: 'John'});
myCollection.add({id: 1, name: 'John'});
console.log(myCollection);
// 結果
// {
// 0: { id: 1, name: 'John' },
// 1: { id: 1, name: 'John' }
// }
そこで、Map を使用します
const myCollection = new Map();
myCollection.set(1, {id: 1, name: 'John'});
myCollection.set(1, {id: 1, name: 'John'}); // 上書きされる
console.log(myCollection); // Map(1) { 1 => { id: 1, name: 'John' } }
// 結果
// Map(1) { 1 => { id: 1, name: 'John' } }
myCollection.set(1, {id: 1, name: 'Paul'});
console.log(myCollection); // Map(1) { 1 => { id: 1, name: 'John' } }
// 結果
// Map(1) { 1 => { id: 1, name: 'Paul' } }
Mapのキーはあらゆる型の値を使用できますが、 オブジェクトの場合は参照先が違うと別の値として考えられます。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
オブジェクトMapはキーと値のペアを保持し、キーの元の挿入順序を記憶します。
任意の値(オブジェクトとプリミティブ値の両方)をキーまたは値として使用できます。