search

Home  >  Q&A  >  body text

javascript - Use localstorage to delete a certain piece of data under a certain key

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?

大家讲道理大家讲道理2733 days ago1386

reply all(6)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-07-03 11:43:49

    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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-03 11:43:49

    The simplest and crudest one

    const data = JSON.parse(localStorage.getItem('contractdata'));
    // ...
    localStorage.setItem('contractdata', JSON.stringify(data));

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-03 11:43:49

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

    reply
    0
  • 巴扎黑

    巴扎黑2017-07-03 11:43:49

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

    reply
    0
  • 世界只因有你

    世界只因有你2017-07-03 11:43:49

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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-07-03 11:43:49

    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.

    reply
    0
  • Cancelreply