Question

I am trying to make a button, which creates some data and saves it in the sessionStorage. I want to give every data a key number from 0 and up. The first time the button is pressed it gets the name/key 0. If the button is then pressed again the name for the new data string/object would be 1 and so on. The thing is that I dont want to overwrite existing data in sessionStorage, so it should check if there is a string/object in the sessionStorage; if yes give it a new name, if no save it.

In my following code, cpData is the data I want to store in sessionStorage:

    for (var index = 0; index <= window.sessionStorage.key(index); index++) {
        if (index > window.sessionStorage.key(index)) {
            window.sessionStorage.setItem(index, cpData);
            break;
        }
    };
Was it helpful?

Solution

I found out by myself. This code should do it if one is needs the to do the same:

for (var index = 0; index >= window.sessionStorage.key(index); index++) {
        if (window.sessionStorage.key(index) === null) {
            window.sessionStorage.setItem(index, JSON.stringify(cpData));
            break;
        } else if (index > window.sessionStorage.key(index)) {
            window.sessionStorage.setItem(index, JSON.stringify(cpData));
            break;
        }
    };

This time it checks wether or not window.sessionStorage.key(index) isn't there. If so it will create a datastring. The break; statement stops the loop immediately. Now the next time the button is pressed and the loop is started, it can see that there is already a datastring, it will then continue to loop until index value is bigger than the key biggest key value at the moment. When it is bigger than al previous saved data, it will save the data and break; the loop.

If one wants to check it by him/herself add this to the same script:

var i = 0, oJson = {}, sKey;
    for (i; sKey = window.sessionStorage.key(i); i++) {
        oJson[sKey] = window.sessionStorage.getItem(sKey);

    }
    console.log(oJson);

This will print out ALL sessionStorage data in console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top