javascript - Use localstorage to delete a certain piece of data under a certain key
大家讲道理
大家讲道理 2017-07-03 11:41:49
0
6
1356

The ones I found seem to be using removeItem and then deleting the key. I would like to ask if there is a more detailed method to delete a certain piece of data under a certain key.
Example

As shown in the picture, if I want to delete the a1709 data in this contrastdata, what should I write?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(6)
我想大声告诉你

Since the contents stored in localStorage are actually strings, what you see is actually the result of the array contrastdata being passed through JSON.stringify and then written to localStorage.

Since the native localStorage only handles the addition, deletion, modification and query of key-value pairs, so to process the item a1709 in contrastdata, you can only array the contrastdata, and then delete the item a1709 Convert it to a string and replace it, the code is as follows:

var contrastdata = JSON.parse(localStorage.getItem('contrastdata')); // 数组化后的值
delete contrastdata['a1709']; // 删除a1709项
localStorage.setItem(JSON.stringify(contrastdata)); // 将删除a1709项后的contrastdata字符串化写回localStorage
我想大声告诉你

The simplest and crudest one

const data = JSON.parse(localStorage.getItem('contractdata'));
// ...
localStorage.setItem('contractdata', JSON.stringify(data));
滿天的星座

The native only provides basic API, you need to encapsulate the functions yourself

巴扎黑

Here, if you want to delete a certain key, another idea is to setItem and replace it with a new contractdata

世界只因有你
  1. Extract contrastdata string str

  2. Convert to object obj

  3. Extract the key-value pair where a1709 is located from the object and delete

  4. Set new contrastdata

let str = localStorage.getItem('contrastdata');
let obj = JSON.parse(str);
delete obj.instrumentIDdate
localStorage.setItem('contrastdata', JSON.stringify(obj))
伊谢尔伦

I think if you want to remove something, first it must have a unique identifier, then find a data set corresponding to this identifier in the data, and then delete the data set. For localstorage, I use it most The method is to push the object to an array, then stringify the array, and then store it in localstorage. When taking it out, you can objectify the string again. Then delete a certain data in the array based on the unique identifier.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template