1

I have a simple app using Express and Node (v12.13.0 on windows). I found that I can not add anything to Set.

I tired to add different type of objects in it but not working at all. Object.prototype.toString.call(aSet) outputs "[object Set]":

let users = new Set();
users.add('1');
console.log('users: ' + JSON.stringify(users));

The above outputs {}, an empty object, despite the fact that the Set has items in it.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
haolun
  • 304
  • 1
  • 9

1 Answers1

3

Sets are not plain objects - they're Set instances, so (just like other objects that aren't plain objects, like dates, regular expressions, functions, etc) they can't be turned into JSON or back. If you want to serialize them, convert them to arrays first (and to deserialize, take the array and pass to new Set):

let users = new Set();
users.add('1');
const arrUsersJSON = JSON.stringify([...users]);
console.log('users: ' + arrUsersJSON);

// Deserialize:
const deserializedArr = JSON.parse(arrUsersJSON);
const deserializedSet = new Set(deserializedArr);
console.log(deserializedSet.has('1'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320