Sets plus JSON

Nicholas C. Zakas standards at
Wed Oct 3 09:37:10 PDT 2012

After a little more experimenting with sets (still a really big fan!!), 
I've come across an interesting problem. Basically, I found myself using 
a set and then wanting to convert that into JSON for storage. 
JSON.stringify() run on a set returns "{}", because it's an object 
without any enumerable properties. I'm wondering if that's the correct 
behavior because a set is really more like an array than it is an 
object, and perhaps it would be best to define a toJSON() method for 
sets such as:

Set.prototype.toJSON = function() {
     return Array.from(this);

That way, JSON.stringify() would do something rational by default when 
used with sets.



Nicholas C. Zakas

More information about the es-discuss mailing list