Languages
[Edit]
EN

JavaScript - JSON stringify Set

0 points
Created by:
Walter
226

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

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