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:
// ONLINE-RUNNER:browser;
const mySet = new Set();
mySet.add({a: 1, b: 2})
console.log(JSON.stringify([...mySet]));
1. Practical example using spread operator
In this example, we use spread operator (...
) to JSON stringify mySet
.
Runnable example:
// ONLINE-RUNNER:browser;
const mySet = new Set();
mySet.add({a: 1, b: 2})
const result = JSON.stringify([...mySet], null, 4);
console.log(result);
2. Using Array.from()
method
In this example, we use Array.from()
method to JSON stringify mySet
.
Runnable example:
// ONLINE-RUNNER:browser;
const mySet = new Set();
mySet.add({a: 1, b: 2})
const result = JSON.stringify(Array.from(mySet), null, 2);
console.log(result);