Reputation: 52
I want to storage an array of objects in local storage but I just can storage one object into the array. All the new objects are overwriting the previous one in index 0.
This is my JavaScript code:
class Track {
constructor (title, genre) {
this.title = title;
this.genre = genre;
this.id = new Date().getTime();
this.creation = new Date();
}
}
class TrackList {
constructor () {
this.tracks = [];
}
newTrack(track) {
this.tracks.push(track);
this.saveLocalStorage();
}
saveLocalStorage() {
localStorage.setItem('tracks', JSON.stringify(this.tracks));
}
}
const addSongForm = document.querySelector('.addSongForm');
addSongForm.addEventListener('submit', (e) => {
const songTitle = document.querySelector('.songTitle').value;
const songGenre = document.querySelector('.songGenre').value;
const newTrackForm = new Track(songTitle, songGenre);
const trackList = new TrackList();
trackList.newTrack(newTrackForm);
});
Thanks in advance!!
Upvotes: 1
Views: 669
Reputation: 111
get the current content of the local storage first and then put the new objects into the array.
var currentTracks = localStorage.getItem('tracks');
localStorage.setItem('tracks', JSON.stringify(JSON.parse(currentTracks).concat(this.tracks)));
EDIT: if the current objects that has the same ID as the new object need to be replaced, the new array needs to be adjusted.
/**
* source : https://www.cnblogs.com/water-1/p/10780528.html
*/
function mergeArray(arr1,arr2){
var _arr = new Array();
for(var i=0;i<arr1.length;i++){
_arr.push(arr1[i]);
}
for(var i=0;i<arr2.length;i++){
var flag = true;
for(var j=0;j<arr1.length;j++){
if(arr2[i]['id']==arr1[j]['id']){
flag=false;
break;
}
}
if(flag){
_arr.push(arr2[i]);
}
}
return _arr;
}
var currentTracks = JSON.parse(localStorage.getItem('tracks'));
localStorage.put('tracks', mergeArray(this.tracks, currentTracks));
Upvotes: 1