stringifying sets

2019-11-01

 | 

~1 min read

 | 

91 words

In Javascript, Sets are Objects with a few special attributes. Notably, they’re iterable collections of unique elements.

One of the consequences of how Sets are constructed, however, is that they’re not stringify-able.1

There are some simple solutions to this is to create an array before trying to stringify the elements.

For example:

const mySet = new Set([1,2,3,4,5,6,1]) // the duplicative 1 will be removed
console.log(JSON.stringify(mySet)) // “{}”
console.log(JSON.stringify([...mySet]) // “[1, 2, 3, 4, 5, 6]”

Footnotes



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!