How do I change a single value inside a localStorage item?

后端 未结 2 1290
不知归路
不知归路 2021-02-11 01:00

I have a set of items that get saved but I\'m trying to change a value after I retrieve it and before I pass it of to my php function. Is it possible to change just one item?

相关标签:
2条回答
  • 2021-02-11 01:13

    Try this

    var args = window.localStorage.getItem("localusers");
    args["type"] = 6;
    
    //Update the localStorage with new value
    localStorage.setItem("localusers", JSON.stringify(args));
    

    Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets.

    var args = localStorage["localusers"];
    args["type"] = 6;
    
    //Update the localStorage with new value
    localStorage["localusers"] = args;
    
    0 讨论(0)
  • 2021-02-11 01:29

    localstorage does not return an array or an object. It can only store a string.

    The way people get around it, is to JSON.stringify() the array/object before passing it to setItem. Then, when retrieving it with getItem(), you run JSON.parse() on it.

    Assuming this is an object, and you've parsed it, you can modify your args variable before you send it along:

    args.type = 6;
    

    To ease all this, here's a little helper that you can call:

    var localstorage = {
        set: function (key, value) {
            window.localStorage.setItem( key, JSON.stringify(value) );
        },
        get: function (key) {
            try {
                return JSON.parse( window.localStorage.getItem(key) );
            } catch (e) {
                return null;
            }
        }
    };
    

    If you include this script, you can then set and get items through localstorage.get and localstorage.set, and it'll automatically convert it to & from JSON.

    0 讨论(0)
提交回复
热议问题