The process of converting data from a form serialization type to an object based on JavaScript (allowing objects to contain objects) _javascript tips

Source: Internet
Author: User
Tags serialization

The data in the form serialization type refers to the format of the data that is passed by the URL, in the form of a Key/value key value pair such as "Key=value&key=value&key=value". The $.fn.serialize function of jquery is generally used to achieve this effect. How do I convert such a format to an object?

We know that using the $.fn.serializearray function of jquery is an object with the following structure

[
  {
    name: ' StartTime '
    value: ' 2015-12-02 00:00:00 '
  },
  {
    name: ' Endtime '
    value: ' 2015-12-25 23:59:59 "
  }
]

This is an array of objects, but sometimes what we want is an object of the following structure

{
  "starttime": "2015-12-02 00:00:00"
  "Endtime": "2015-12-25 23:59:59"
}

So here we need a transformation function.

The processing steps are as follows:

1. Use the "&" separator to separate each key-value pair and then loop through each key-value pair

  var properties = Serializedparams.split ("&");
  for (var i = 0; i < properties.length i++) {
    //process each key value pair
    Evalthem (Properties[i]);
  

2. Splits the specified key-value pairs from the "=" symbol and uses decodeURIComponent to parse the URI component encoding for each key and value (because the serialized data passed by the URL is typically encoded by the URI component)

    var strary = new Array ();
    Strary = Str.split ("=");
    Use decodeURIComponent parsing URI component encoding for
    (var i = 0; i < strary.length i++) {
      Strary[i] = decodeuricomponent ( Strary[i]);
    }
    var attributename = strary[0];
    

3. If the value contains the "=" symbol, additional processing is required (value consolidation).

 if (Strary.length > 2) {for
      (var i = 2;i<strary.length;i++) {
        AttributeValue + = "=" +strary[i].trim ();
      }
    

There's a deal in it that doesn't add to the final object when the value is not there. This can be selected according to their own circumstances to delete this code or not

   if (!attributevalue) {return
      ;
    

4. If the key is "Obj.obj.obj" this by "." Symbolic link, it needs to be handled as an object containing object. The way to handle this is to pass the key through "." And then see if the temporary object obj already contains the decomposed object, and if so, append the data to an existing object. Source code is as follows

 var attrinames = Attributename.split ("."),
      curobj = obj;
    for (var i = 0; i < (attrinames.length-1); i++) {
      curobj[attrinames[i]]? "":( Curobj[attrinames[i]] = {});
      Curobj = Curobj[attrinames[i]];
    }
    

This is what we see on the Internet, where the assignment part is handled.

 
 

This is a problem, one is that the object containing objects in 4 is not handled correctly (especially if two elements have the same parent object, such as "Test.id=1&test.name= ' Chua" has the parent object test). The other is that the value AttributeValue is not handled correctly when it contains single quotes and double quotes. So use the assignment "=" the most insurance.

So the final complete source code is as follows

/* serializedparams format is "Key1=value1&key2=value2".
  also supports ' key.sonkey=value '/function Paramstring2obj (serializedparams) {var obj={};
    function Evalthem (str) {var strary = new Array ();
    Strary = Str.split ("="); Use decodeURIComponent parsing URI component encoding for (var i = 0; i < strary.length i++) {Strary[i] = decodeURIComponent (strar
    Y[i]);
    var attributename = strary[0];
    var attributevalue = Strary[1].trim (); If the value contains the "=" symbol, you need to merge the value if (Strary.length > 2) {for (var i = 2;i<strary.length;i++) {AttributeValue = "
      = "+strary[i].trim ();
    } if (!attributevalue) {return;
    var attrinames = Attributename.split ("."), curobj = obj; for (var i = 0; i < (attrinames.length-1); i++) {curobj[attrinames[i]]? "":(
      Curobj[attrinames[i]] = {});
    Curobj = Curobj[attrinames[i]]; ///Use assignment method Obj[attributename] = Attributevalue.trim (); Replace//eval ("obj." +attributename+ "=\" "+attributevalue.trim" ()+"\";");
  Resolves problems in value attributevalue that cannot be handled with single or double quotes curobj[attrinames[i] = Attributevalue.trim ();
  };
  var properties = Serializedparams.split ("&");
  for (var i = 0; i < properties.length i++) {//process each key value pair Evalthem (Properties[i]);
  };
return obj; }

The above content is based on JavaScript converting form serialization type data to object processing (allowing objects to contain objects), and I hope this article can help you to share.

Related Article

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.