简体   繁体   中英

javascript es6 set feature

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 ie two objects will be same if the values of their ID's are same.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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