localStorage.removeItem() 不从对象中删除 key/value

localStorage.removeItem() not removing key/value from object

正在努力解决这个问题...

我正在尝试从我的 localStorage 对象中删除 key/value 对。但是,没有任何内容被删除。 (我也没有任何错误)。

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

   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 delete reena

谢谢!

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

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