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;
};
13
  • there's no code there regarding local storage. Commented Oct 5, 2015 at 12:23
  • I dunno where should i start with the localStorage. That's why i'm looking for some help. :) Commented Oct 5, 2015 at 12:24
  • so the code snippet is totally irrelevant, just checking Commented Oct 5, 2015 at 12:25
  • read the answer would be my first piece of advice Commented Oct 5, 2015 at 12:27
  • Why you want to use localstorage ? Commented Oct 5, 2015 at 12:27

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If i refresh the page, will the data remain or not ?
For such questions please see the documentation cited by @Buzinas Mozilla documentation. 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.
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);

7 Comments

Yeah, but how can i access it again so that i can sort it and display it in my project?
Use the line Read the object
After i parse the object, can i access the array like this again? obj.Players[0].score
Okay, i'll try it. I will just comment if it works . thanks (Y)
@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.
|
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.

2 Comments

After i parse it, can i access the object again like this ? obj.Players[i].score
@DarbsLingo yeah, you can :)
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 '{}' 

2 Comments

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
Thank you so much for the feedback. I've updated my answer, just let me know if the explanation is correct or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.