好的,所以我在LocalStorage中存储了这样的JSON:

[{"pseudo":"Lucia","id":2},{"pseudo":"Romain","id":1}]


我搜索了如何删除一项,但只找到了这一点:

storage.removeItem(keyName);


但是,如果我错了,请纠正我,如果我这样做,如果我执行storage.removeItem(pseudo);它将删除keyName为“ pseudo”的所有值。

如何仅从json中删除{"pseudo":"Romain","id":1}并保留{"pseudo":"Lucia","id":2}

谢谢。

最佳答案

localstorage仅支持字符串值,因此您需要解析数据。

    var storedNames = JSON.parse(localStorage.getItem("keyName"));

    // here you need to make a loop to find the index of item to delete
    var indexToRemove = 1;

    //remove item selected, second parameter is the number of items to delete
    storedNames.slice(indexToRemove, 1);

   // Put the object into storage
   localStorage.setItem('keyName', JSON.stringify(storedNames));

08-19 15:24