3

I am developing a game in HTML5 for my project, my problem is in the scoring system.
I want to display the top ten best scorers (already sorted). I am currently working with Array in a JSON.

Now I want to save JSON Array in localStorage

var storage = '{"Players":[' +
        '{"score":"0","Name":"Player 2"},' +
        '{"score":"0","Name":"Player 4"},' +
        '{"score":"0","Name":"Player 1"}]}';

var obj = JSON.parse(storage);

obj['Players'].push({"score": 13,"Name": "Player1"});
obj['Players'].push({"score": 523,"Name": "Player2"});
obj['Players'].push({"score": 3,"Name": "Player3"});
obj['Players'].push({"score": 1235,"Name": "Player4"});

storage = JSON.stringify(obj);

var sortColumnScore = "score";

function SortByScore(x,y) {
    return ((x[sortColumnScore]  == y[sortColumnScore]) ? 0 : ((x[sortColumnScore] < y[sortColumnScore]) ? 1 : -1 ));
}

obj.Players.sort(SortByScore);

for (var i = 0; i < 5; i++) {
    document.getElementById("s"+ (i+1)).innerHTML =
    obj.Players[i].score;
    document.getElementById("p"+ (i+1)).innerHTML =
    obj.Players[i].Name;
};
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Darbs Lingo
  • 33
  • 1
  • 4

4 Answers4

2

Basically you should use localstorage just like you are doing with storage above. You can use localstorage in the object way as is doing @Magus or in the associative-array way, calling its primitives getItem, setItem.

Simple usage:

var storage = '{"Players":[' +
    '{"score":"0","Name":"Player 2"},' +
    '{"score":"0","Name":"Player 4"},' +
    '{"score":"0","Name":"Player 1"}]}';

var obj = JSON.parse(storage);

obj['Players'].push({"score": 13,"Name": "Player1"});
obj['Players'].push({"score": 523,"Name": "Player2"});
obj['Players'].push({"score": 3,"Name": "Player3"});
obj['Players'].push({"score": 1235,"Name": "Player4"});

localStorage.setItem('Players', JSON.stringify(obj));

Then get data from localStorage calling:

var myobj = JSON.parse(localStorage.getItem('Players'));

Advanced usage:

For correct usage (coupled with the current user session) and initialization of localstorage/sessionstorage (according to your goal) see the comment of @War10ck following this issue Push JSON Objects to array in localStorage.

Community
  • 1
  • 1
morels
  • 2,095
  • 17
  • 24
  • If i refresh the page, will the data remain or not ? – Darbs Lingo Oct 05 '15 at 12:51
  • For such questions please see the documentation cited by @Buzinas [Mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). Anyway, the localStorage keeps data even if you close the window and reopen it later. The sessionStorage keeps data only in the same session (i.e. same tab of the browser), instead. – morels Oct 05 '15 at 13:18
0

The localStorage can't contains object or array. But you can convert it in a string.

// Store the object
localStorage.myObject = JSON.stringify(myObject);

// Read the object
var myObject = JSON.parse(localStorage.myObject);
Magus
  • 14,796
  • 3
  • 36
  • 51
  • Yeah, but how can i access it again so that i can sort it and display it in my project? – Darbs Lingo Oct 05 '15 at 12:28
  • Use the line `Read the object` – Magus Oct 05 '15 at 12:28
  • After i parse the object, can i access the array like this again? `obj.Players[0].score` – Darbs Lingo Oct 05 '15 at 12:31
  • Okay, i'll try it. I will just comment if it works . thanks (Y) – Darbs Lingo Oct 05 '15 at 12:33
  • @Magus although it will work, it won't work if he refreshes the page, since that's not a correct way to use localStorage. If you set items to the localStorage like this, you're only creating a property into it, as you could do `window.myObject =`, or `document.myObject =` etc. – Buzinas Oct 05 '15 at 12:36
  • It works like this too. See this response : http://stackoverflow.com/questions/3357553/how-to-store-an-array-in-localstorage?rq=1 – Magus Oct 05 '15 at 12:39
  • @Buzinas That's my next problem. Would you mind helping me? T.I.A (y) – Darbs Lingo Oct 05 '15 at 12:45
0

Getting an item from localStorage:

var str = localStorage.getItem('my-item');

Saving an item in localStorage:

localStorage.setItem('my-item', str);

Note: You can only save strings to the localStorage, so, you will need to convert your data to string via JSON.stringify and then use JSON.parse when retrieving the strings from localStorage.

Buzinas
  • 11,597
  • 2
  • 36
  • 58
0
// To store object into local storage
localStorage.setItem('any-unique-key', JSON.stringify(arrayName));


// To retrieve from local storage
var resultArray = JSON.parse(localStorage.getItem('any-unique-key') || '{}'); 


// Check if the data associated with that 'any-unique-key' exists or not
// If not then return empty JSON object enclosed with single quotes
return '{}' 
  • This is pretty much the same as the top answer, except for that `|| '{}'`. To improve your answer it would better to explain the difference/benefit of using your way compared to the existing 6 years old answer... Please [edit] your answer with that information – Tomerikoo Dec 09 '21 at 09:09
  • Thank you so much for the feedback. I've updated my answer, just let me know if the explanation is correct or not. – Akash Starvin Dsouza Dec 09 '21 at 14:21