Make localstorage more efficient to access JSON

Source: Internet
Author: User

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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.