'How do I save all my created variables to local storage? (Javascript/HTML)

Straight to the point. I am in the process of making a game right now, I have come to the point where I want to save all my variables to the local storage.

And YES I know the good ol' way:

localStorage.setItem("var1", 5)

var1 = parseInt(localStorage.getItem("var1"))

That's all good and all, but I have WAYYY to many variables to type all that out manually, Is there a way to save all my variables to local storage with only a couple lines of code? then on refresh, set all variables back to there corresponding value in local storage



Solution 1:[1]

Why not instead of using many variables just use one object? Then you save it once and read it once:

let variables = {
    "var1" : 5,
    "var2" : 10
};
 
localStorage.setItem("vars", JSON.stringify(variables));
...
let variables = JSON.parse(localStorage.getItem("vars"));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1