【问题标题】:Trying to get index of object in localstorage so I can delete/remove that object from localStorage storage, using javascript or jquery试图在 localstorage 中获取对象的索引,以便我可以使用 javascript 或 jquery 从 localStorage 存储中删除/删除该对象
【发布时间】:2019-03-07 03:50:47
【问题描述】:

所有,这是我在这里的第一个问题,所以我希望我的措辞正确并提供足够的信息来处理。

我在本地存储中有一个名为 faveGifs 的键,其中存储了几个项目,每个项目都是一个对象。我希望能够单独删除这些对象。到目前为止,我可以删除第一个对象,即位置 0 的对象。我希望能够在它们所在的任何索引处删除它们,例如位置 2。我知道我必须获取每个对象的索引才能实现这一点,但是,当我通过 indexOf() 运行密钥时,我得到的唯一索引是 -1。

这是我的本地存储密钥的外观:

faveGifs[
  {id: 'jijijoj',rating: 'g'}, 
  {id: 'iojiojoi',rating: 'r'}, 
  {id: 'eawfe',rating: 'pg'}, 
  {id: 'ewfewfwe',rating: 'g'}, 
  {id: 'ewfewfew',rating: 'r'}
];

这是我的代码:

$(document).on("click", "#remove", function () {
  let faveGifs = JSON.parse(localStorage.getItem("faveGifs"));
  let faveGif = faveGifs.map(faveGif => faveGif.id);

  //Neither of the following has worked for me:

  //let index = faveGif.indexOf(faveGif);
  //let index = faveGif.indexOf(faveGifs);
  console.log(index);

  // faveGifs.splice(index, 1);
  // localStorage.setItem("faveGifs", JSON.stringify(faveGifs));
  // populateFaves();
});

我曾尝试使用类似问题的解决方案,但没有一个对我有用。我试过的有:

Remove a specific item from localstorage with js

Remove json object in localstorage using js

How do I remove an object from an array with JavaScript?

还有其他几个,但就像我说的,没有一个对我有用。

非常感谢帮助我的所有人。

【问题讨论】:

    标签: javascript jquery arrays json object


    【解决方案1】:

    问题是 faveGif 仍然是一个数组 - 它看起来像这样:

    faveGif = ['jijijoj', 'iojiojoi', 'eawfe', 'ewfewfwe', 'ewfewfew'];
    

    所以如果你想找到某个ID的索引(比如ewfewfew):

    let index = faveGif.findIndex(id => id == "ewfewfew");
    

    这将与faveGifs 中的索引相同,因此它会为您提供所需的结果。

    演示:

    let faveGifs = [{
      id: 'jijijoj',
      rating: 'g'
    }, {
      id: 'iojiojoi',
      rating: 'r'
    }, {
      id: 'eawfe',
      rating: 'pg'
    }, {
      id: 'ewfewfwe',
      rating: 'g'
    }, {
      id: 'ewfewfew',
      rating: 'r'
    }];
    
    let faveGif = faveGifs.map(faveGif => faveGif.id);
    
    let index = faveGif.findIndex(id => id == "ewfewfew");
    
    console.log(index); //Should return 4

    【讨论】:

      【解决方案2】:

      要获取数组中元素的索引,您可以使用Array.prototype.findIndex()

      代码:

      const data = [
        {id: 'jijijoj',rating: 'g'}, 
        {id: 'iojiojoi',rating: 'r'}, 
        {id: 'eawfe',rating: 'pg'}, 
        {id: 'ewfewfwe',rating: 'g'}, 
        {id: 'ewfewfew',rating: 'r'}
      ];
      
      // get index of element with id `iojiojoi`
      const index = data.findIndex(item => item.id === 'iojiojoi');
      
      console.log(index);

      【讨论】:

        【解决方案3】:

        我相信你正在尝试解析一个字符串,就像它是 JSON 一样。

        查看这篇文章:Storing Objects in HTML5 localStorage。 OP 正试图解决类似的问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-14
          • 2015-08-01
          • 1970-01-01
          • 2015-04-23
          • 1970-01-01
          • 2019-02-12
          相关资源
          最近更新 更多