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:
JavaScript
x
39
39
1
class Track {
2
3
constructor (title, genre) {
4
this.title = title;
5
this.genre = genre;
6
this.id = new Date().getTime();
7
this.creation = new Date();
8
}
9
}
10
11
class TrackList {
12
13
constructor () {
14
this.tracks = [];
15
}
16
17
newTrack(track) {
18
this.tracks.push(track);
19
this.saveLocalStorage();
20
}
21
22
saveLocalStorage() {
23
localStorage.setItem('tracks', JSON.stringify(this.tracks));
24
}
25
}
26
27
const addSongForm = document.querySelector('.addSongForm');
28
29
30
addSongForm.addEventListener('submit', (e) => {
31
const songTitle = document.querySelector('.songTitle').value;
32
const songGenre = document.querySelector('.songGenre').value;
33
34
const newTrackForm = new Track(songTitle, songGenre);
35
36
const trackList = new TrackList();
37
trackList.newTrack(newTrackForm);
38
});
39
Thanks in advance!!
Advertisement
Answer
get the current content of the local storage first and then put the new objects into the array.
JavaScript
1
3
1
var currentTracks = localStorage.getItem('tracks');
2
localStorage.setItem('tracks', JSON.stringify(JSON.parse(currentTracks).concat(this.tracks)));
3
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.
JavaScript
1
26
26
1
/**
2
* source : https://www.cnblogs.com/water-1/p/10780528.html
3
*/
4
function mergeArray(arr1,arr2){
5
var _arr = new Array();
6
for(var i=0;i<arr1.length;i++){
7
_arr.push(arr1[i]);
8
}
9
for(var i=0;i<arr2.length;i++){
10
var flag = true;
11
for(var j=0;j<arr1.length;j++){
12
if(arr2[i]['id']==arr1[j]['id']){
13
flag=false;
14
break;
15
}
16
}
17
if(flag){
18
_arr.push(arr2[i]);
19
}
20
}
21
return _arr;
22
}
23
24
var currentTracks = JSON.parse(localStorage.getItem('tracks'));
25
localStorage.put('tracks', mergeArray(this.tracks, currentTracks));
26