Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and retrieve Set from localStorage

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?

like image 529
Manos Kounelakis Avatar asked Nov 05 '25 10:11

Manos Kounelakis


1 Answers

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);
like image 129
Estus Flask Avatar answered Nov 07 '25 04:11

Estus Flask