I have the following code that creates a Set
var foo = new Set();
foo.add(1);
foo.add(2);
Now I store it into localStorage:
localStorage.setItem("set",foo);
However If I try to retrieve it like this:
var x = localStorage.getItem("set");
I get an "[object Set]" as the result.Any Ideas how I can retrieve the actual set?
In order to do that, a set should be converted to an array first.
It can be done by using ES6 iteration:
const fooArr = [...foo];
Or if the code is supposed to be transpiled to ES5, it better should be Array.from, because it is easily polyfillable. Then it can be stringified and stored:
const fooArr = Array.from(foo);
localStorage.setItem('set', JSON.stringify(fooArr));
And retrieved in reverse:
const fooArr = JSON.parse(localStorage.getItem('set'));
const foo = new Set(...fooArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With