EN
JavaScript - JSON stringify Set
0 points
In this article, we would like to show you how to JSON stringify a set in JavaScript.
Quick solution:
xxxxxxxxxx
1
const mySet = new Set();
2
mySet.add({a: 1, b: 2})
3
4
console.log(JSON.stringify([mySet]));
In this example, we use spread operator (...
) to JSON stringify mySet
.
Runnable example:
xxxxxxxxxx
1
const mySet = new Set();
2
mySet.add({a: 1, b: 2})
3
4
const result = JSON.stringify([mySet], null, 4);
5
6
console.log(result);
In this example, we use Array.from()
method to JSON stringify mySet
.
Runnable example:
xxxxxxxxxx
1
const mySet = new Set();
2
mySet.add({a: 1, b: 2})
3
4
const result = JSON.stringify(Array.from(mySet), null, 2);
5
6
console.log(result);