开发者

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

开发者 https://www.devze.com 2023-03-30 20:25 出处:网络
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?

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?

My string of items looks like this:

var args = window.localStorage.getItem("localusers");

start=0&type=1

I'm saving the localusers item like so:

window.localStorage.setItem('localusers', $("#profile_form_id").serialize());

I'm trying to set the value of type to a 6

I can't find a supported 开发者_开发百科method that allows me to get/set an item in the array so do I need to iterate through the array, change the value and then set the localusers item again? It doesn't seem very efficient but I can't see any other way.

Any thoughts or suggestions?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号