Reputation: 190
Hello guys I have a question. I have made a calendar and everything works, but the last requirement is to add dates through localStorage
.
So my question: how can I add more dates without overwriting the first one?
I was thinking about getting the data out, add the new testObject
, and put it back to localStorage
. The only thing is I have no clue how to do it.
I hope someone can help. ( I am quite a beginner )
So in short, I want to put more than one array into the events
-array through localStorage
.
This is my code:
<script language="JavaScript" type="text/javascript" >
testObject = ["Y", prompt("maand"), prompt("dag"), "2000", prompt("test"), prompt("test")]
retrievedObject = localStorage.getItem('testObject');
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject))
events = new Array(
JSON.parse(retrievedObject),
["Y", "1", "1", "2000", "Nieuw jaars dag", "De eerste dag van het nieuw Jaar"],
["Y", "7", "3", "2000", "Mijn verjaardag", "beste dag van het jaar"],
["Y", "17", "10", "2000", "Inleverdag", "Ergste dag van het jaar."]
);
</script>
Edit : after I add 2 arrays it should Work like this But the upper 2 values should be retrieved form local storage and if I add another one it should be 3 arrays in the local storage. But the local storage overwrites itself everytime So at the moment I am only able to add 1 array
events = new Array(
["Y", "1", "2", "2000", "test", "test"],
["Y", "2", "4", "2000", "test2", "test3"],
["Y", "1", "1", "2000", "Nieuw jaars dag", "De eerste dag van het nieuw Jaar"],
["Y", "7", "3", "2000", "Mijn verjaardag", "beste dag van het jaar"],
["Y", "17", "10", "2000", "Inleverdag", "Ergste dag van het jaar."]
);
Upvotes: 0
Views: 148
Reputation: 10084
I think the confusion is in your wording, Your asking how to add data to an array but the code examples you provide don't do any adding at all.
I think what your after is Array.prototype.push
and Array.prototype.concat
.
In an effort to show and example I will make the following assumptions of what you want to do:
// Helper to easily create a new test object
function buildTestObject() {
return [
'Y',
prompt('maand'),
prompt('dag'),
'2000',
prompt('test'),
prompt('test')
];
}
// Pull in the old value from localStorage
var retrievedObject = localStorage.getItem('testObjects') || '[]';
try {
// Turn JSON into JS Object
retrievedObject = JSON.parse(retrievedObject);
} catch (e) {
retrievedObject = [];
}
// Actually add a testObject to the array which will be stored in localStorage
retrievedObject.push(buildTestObject());
// Save the now mutated array of testObjects back into localStorage
localStorage.setItem('testObject', JSON.stringify(retrievedObject))
var events = retrievedObject.concat(
["Y", "1", "1", "2000", "Nieuw jaars dag", "De eerste dag van het nieuw Jaar"],
["Y", "7", "3", "2000", "Mijn verjaardag", "beste dag van het jaar"],
["Y", "17", "10", "2000", "Inleverdag", "Ergste dag van het jaar."]
);
Upvotes: 1