localStorage.removeItem()不会从对象中删除键/值

时间:2019-12-03 10:36:03

标签: javascript arrays object local-storage web-storage

努力找出这一点...

我正在尝试从localStorage对象中删除键/值对。但是,没有任何东西被删除。 (我也没有任何错误)。

我知道我可以通过其键名删除有问题的键/值。这是该对象的示例:

   bookMarksArray:    [
        {
            "name": "reena",
            "url": "brian"
        },
        {
            "name": "joe",
            "url": "ault"
        }
       ]

这是我的代码...我正在使用事件目标来获取键名并将其与对象索引匹配。

然后将该对象索引的键传递到 localStorage.removeItem() ...我在做什么错了?

  list.addEventListener('click', event => {
    if (event.target.classList.contains('js-delete-url')) {

      const editName = event.target.parentElement.name.value;
      const objIndex = bookMarksArray.findIndex(obj => obj.name === editName);

      localStorage.removeItem(bookMarksArray[objIndex].name);
      console.log('delete', bookMarksArray[objIndex].name);
    }
  });

控制台将打印以下内容:

  

app.js:55删除reena

谢谢!

2 个答案:

答案 0 :(得分:2)

LocalStoage将值保存为字符串格式,因此每次必须将JSON对象进行字符串化才能将其保存在localStorage中,我们可以解决此问题,请找到下面的代码段,在这种情况下很有用,

var updateStorage = function(filterName) {
	var bookMarksArray=   [{"name": "reena", "url": "brian"}, {"name": "joe", "url": "ault"}]
	localStorage.setItem('nameList', JSON.stringify(bookMarksArray));
      var items = JSON.parse(localStorage.getItem('nameList'));
	var updatedList = items.filter(function(a) {
          return a.name !== filterName;
      });
	localStorage.setItem('nameList', JSON.stringify(updatedList));
	console.log(localStorage.getItem('nameList'));
    // result [{"name":"reena","url":"brian"}]
};
updateStorage('joe');

答案 1 :(得分:0)

//set js object to localstorage
localStorage.setItem('bookMarksArray',JSON.stringify(bookMarksArray))

//get js object from localstorage
bookMarksArray= JSON.parse(localStorage.getItem('bookMarksArray'))

//remove desired item
bookMarksArray = bookMarksArray.filter(function(item) {
    return item.name !== 'reena';
});

//update js object in localstorage
localStorage.setItem('bookMarksArray',JSON.stringify(bookMarksArray))