本地存储-删除部分包含字符串的密钥

时间:2019-02-07 13:07:54

标签: javascript local-storage

我已为用户提供了将某些信息保存到本地存储的选项。 因此,当他们查看项目并单击保存时,我将根据项目ID创建密钥。这是添加了3个项目的键的示例:

saved-items: ["31919988", "2424334", "6436366"]

如果他们选择删除特定的物品,我会在其中 cid是物品ID 的地方拼接ID:

names = JSON.parse(localStorage.getItem('saved-items'));
var index = names.indexOf(cid);
 if (index > -1) {
   names.splice(index, 1);
 }    
localStorage.setItem("saved-items", JSON.stringify(names));  

这一直很好,但是当他们选择从第一个键中删除项目时,我需要删除第二个键。

saved-items-price: ["31919988_5.88", "2424334_12.02", "6436366_04.32"]

因此,如果用户选择删除“ 31919988”项,则如上所述将其从第一个键中删除,但是我还需要从第二个键中将其删除,但 indexOf 自然会返回false,因为这不是完全匹配。

将两个键值匹配在一起并删除它们的最佳方法是什么?

5 个答案:

答案 0 :(得分:2)

您可以在处理string.split的每个项目之前简单地saved_item_price

const names = JSON.parse(localStorage.getItem('saved-items-price'));
const updatedNames = names.filter(name => name.split('_')[0] !== cid);
localStorage.setItem("saved-items", JSON.stringify(updatedNames));  

答案 1 :(得分:2)

您为什么不只使用一个单个键?您可以为每个项目设置一个Object,并使用idprice之类的属性来存储数据。

// define items
var item1 = {id: 31919988, price: 5.88};
var item2 = {id: 2424334, price: 12.02};
var item3 = {id: 6436366, price: 04.32};
...
// save all items in an array in localStorage
localStorage.setItem('saved-items', JSON.stringify([item1,item2,item3]));
...
// get items for localStorage
var items = JSON.parse(localStorage.getItem('saved-items'));
// get items except for the one(s) you want to remove
var newItems = items.filter(item => item.id != 31919988);
// save back to localStorage
localStorage.setItem('saved-items', JSON.stringify(newItems));

答案 2 :(得分:1)

您可以像这样获得数组的键:

var list = ["31919988_5.88", "2424334_12.02", "6436366_04.32"];
var search = "31919988"
var index = list.find(function(element, k) {
  return element.startsWith(search)
})
const key = Object.keys(list).find(key => list[key] === index);
console.log(key)

答案 3 :(得分:0)

尝试一下:

var itemPrices = ["31919988_5.88", "2424334_12.02", "6436366_04.32"];
var newItemPrices = itemPrices.filter(item => item.indexOf("31919988") == -1);

答案 4 :(得分:0)

让价格= [“ 31919988_5.88”,“ 2424334_12.02”,“ 6436366_04.32”]; 让newPrices = prices.filter(item =>!item.includes(“ 31919988”));