Js: Multiple Objects In An Array Stored In Local Storage
I've been trying to do this all day and just can't get it right. I've read many articles on various websites and tried many different approaches, but I am still getting issues of o
Solution 1:
You are pushing entire array received from local storage into second position of local showList array, you should use array concatenation:
localStorage.removeItem('showList');
functionaddNewShow(titleArg, typeArg, genreArg, watchedArg) {
var showList = [];
var show = {
title: titleArg,
type: typeArg,
genre: genreArg,
watched: watchedArg
};
showList.push(show);
showList = showList.concat(JSON.parse(localStorage.getItem('showList')||'[]'));
console.log(showList);
localStorage.setItem("showList", JSON.stringify(showList));
};
addNewShow(1,2,3,4);
addNewShow(1,2,3,5);
addNewShow(1,2,3,6);
addNewShow(1,2,3,7);
Little snippet showing why (jsonString||"[]") is important:
var array = [1,2,3,4];
console.log("array is:");
console.log("\t", array );
console.log("concating null adds new null element to the array");
console.log("\t", array.concat(null) );
console.log("concating empty array deosn't change anything");
console.log("\t", array.concat([]) );
console.log("result of expresion (null||[]) is empty array not null");
console.log("\t", null||[]);
console.log("puting it all together, if we don't want to add null to the array then we can write array.concat( null||[] )");
console.log("\t", array.concat( null||[] ) );
console.log('additionaly JSON.parse(null) in null');
console.log("\t", JSON.parse(null) );
Array.concat just works that way - MDN is great source of documentation and examples - here for concat.
Solution 2:
You should read showList
from localStorage first, then push show
onto that array.
functionaddNewShow(titleArg, typeArg, genreArg, watchedArg) {
// Get array from local storage, defaulting to empty array if it's not yet setvar showList = JSON.parse(localStorage.getItem('showList') || "[]");
var show = {
title: titleArg,
type: typeArg,
genre: genreArg,
watched: watchedArg
};
showList.push(show);
localStorage.setItem("showList", JSON.stringify(showList));
};
Solution 3:
first check for localstorage, then you can use spread operator for iteration
functionaddNewShow(titleArg, typeArg, genreArg, watchedArg) {
var showList = [];
var show = {
title: titleArg,
type: typeArg,
genre: genreArg,
watched: watchedArg
};
showList.push(show);
var finalArr = localStorage.getItem('showList') != undefined ? [...showList, ...JSON.parse(localStorage.getItem('showList'))] : showList;
localStorage.setItem("showList", JSON.stringify(finalArr));
};
Post a Comment for "Js: Multiple Objects In An Array Stored In Local Storage"