[英]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. 我通过按钮上的OnClick()
将对象添加到本地存储阵列中。
$(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
. 我想删除的对象first
从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. ID将使您的对象具有唯一键。 Update will also be easy. 更新也将很容易。
And store these in a JSON object and not an array like 并将它们存储在JSON对象中,而不是像
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. 最好是一个函数,它不仅可以更改数组,还可以将其存储在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. 为了使运行的stackSnippet,我不得不删除localStorage功能,它被注释掉了。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.