Languages
[Edit]
EN

JavaScript - JSON stringify Set

0 points
Created by:
Walter
586

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);

See also

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join