To save an OBJ object to localstorage, perform the following steps: OBJ => objstr = JSON. stringify (OBJ) => localstorage. setitem (name, objstr );
To retrieve a localstorage and convert it to an OBJ object, follow the steps below: objstr = localsotrage. getitem (name) => OBJ = JSON. parse (objstr );
Now it seems that there is no problem. If you want to modify an attribute of OBJ saved in localstorage, you must first retrieve, modify, and save it; in this way, a large amount of JSON conversion and localstorage access need to be written.CodeAnd the risk of incorrect access name. To solve this problem, encapsulate the built-in method.
VaR Wrapjsonstorage = Function (Name ){ VaR Ls = localstorage, Lo = ls. getitem (name) | '{}' ; Try {Lo =JSON. parse (LO ); // Determine whether Lo is an object Lo = Object (LO) = Lo? Lo :{};} Catch (E) {Lo = {};} Return {Has: Function (ATTR ){ Return !! Lo [ATTR] ;}, get: Function (ATTR ){ Return Lo [ATTR] ;}, set: Function (ATTR, Val) {lo [ATTR] = Val; Return This ;}, Remove: Function (ATTR ){ Delete Lo [ATTR]; Return This ;}, Clear: Function () {Lo = {}; Return This ;}, Save: Function (){ // If Lo is null, localstorage is deleted. If ( This . Size ()> 0) {Ls. setitem (name, JSON. stringify (LO ));} Else {Ls. removeitem (name );} Return This ;}, Size: Function (){ Return Object. Keys (LO). length;}, tojson: Function (){ VaR O ={}, I; For (I In Lo) {o [I] = Lo [I];} Return O ;}, tostring: Function (){ Return JSON. stringify (LO );}};};
Usage:
Note: after the set, remove, and clear methods are used, the SAVE method is called to synchronize data to localstorage. This is mainly used to reduce the number of Io operations and increase efficiency.