Slasher
Slasher

Reputation: 618

How to remove object from array in local storage?

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"}]

Upvotes: 1

Views: 3174

Answers (3)

Saksham
Saksham

Reputation: 9390

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.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138557

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.

Upvotes: 2

Eugen Halca
Eugen Halca

Reputation: 1785

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));

Upvotes: 0

Related Questions