I have array like this:
var myMovie = [];
And object like this:
var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
I added object into local storage array via OnClick()
on button.
$(document).ready(function() {
$(".btn.btn-outline-success").click(function () {
myMovie.push(first);
localStorage.setItem('myMovie', JSON.stringify(myMovie));
var output = JSON.parse(localStorage.getItem('myMovie'));
After adding object into local storage, local storage looks like this:
[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]
My question here is, how could I remove whole object via variable name? I want to remove object first
from myMovie
. Index position of object may be different each time.
[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]
I would advice you to have your object in format
var first = {"tt3783958": { title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}}
ID will make your object have unique keys. Update will also be easy.
And store these in a JSON object and not an array like
myMovie = {}; //note its an object
This would make it easier for you to query and delete items.
Best would be a function, that not only changes the array but also stores it in localStorage.
To find the right index to remove, you could find the object with the right title:
var myMovie=[] //JSON.parse(localStorage.getItem('myMovie')||"[]"); function push(el){ myMovie.push(el); //localStorage.setItem('myMovie', JSON.stringify(myMovie)); } function remove(title){ var i=myMovie.findIndex(movie=>movie.title===title); if(i!==-1){ myMovie.splice(i,1); //localStorage.setItem('myMovie', JSON.stringify(myMovie)); } } push({id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}); console.log(myMovie); remove("La La Land"); console.log(myMovie);
To make a running stackSnippet, i had to remove the localStorage functionality, it is commented out.
you need to get the object and set new one:
myMovie = JSON.parse(localStorage.getItem("myMovie"));
myMovie.splice(0,1);
localStorage.setItem("myMovie",JSON.stringify(myMovie));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.