Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

jquery - Localstorage & JSON: How can I delete only 1 array inside a key since localstorage.removeItem requires the entire key

I have this in my localStorage:

[{"id":"item-1","href":"google.com","icon":"google.com"},
{"id":"item-2","href":"youtube.com","icon":"youtube.com"},
{"id":"item-3","href":"google.com","icon":"google.com"},
{"id":"item-4","href":"google.com","icon":"google.com"},
{"id":"item-5","href":"youtube.com","icon":"youtube.com"},
{"id":"item-6","href":"asos.com","icon":"asos.com"},
{"id":"item-7","href":"google.com","icon":"google.com"},
{"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}]

How can I delete only the id:item-3 when localstorage.removeItem requires entire key?

I use this method to update a specific value in an array: http://jsfiddle.net/Qmm9g/ so using the same method I want to delete specific array.

Note that there is already a button to delete. That button I want a function which will delete the entire array ({"id":"item-3","href":"google.com","icon":"google.com"}) with ID:item-3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this would work, I'm not sure if it's the best way to do it though. There maybe a better local storage specific way -

var json = JSON.parse(localStorage["results"]);
for (i=0;i<json.length;i++)
            if (json[i].id == 'item-3') json.splice(i,1);
localStorage["results"] = JSON.stringify(json);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...