需要将带有方括号的字段名称转换为javascript对象

I would like to convert a field name consisting of square brackets into an object in JavaScript. I have seen that PHP does convert them into an array but haven't seen one done in JavaScript despite of searching for one for several days.

Data:

<input name="address[permanent][name]" type="text" value="My Address">
<input name="address[permanent][street][street_one]" type="text" value="My Street One">
<input name="address[permanent][street][street_two]" type="text" value="My Street Two">

Result (what i want to achieve):

form = { address: { permanent: { name: "My Address", street: { street_one: "My Street One", street_two: "My Street Two" } } } }

Untested, but your basic algorithm could be something like this:

The following works for me:

var form = {};
$(':input', yourFormElement).each(function(){
  var top = form;
  var path = $(this).attr('name');
  var val = $(this).val();
  var prev = '';
  while ((path.replace(/^(\[?\w+\]?)(.*)$/, function(_m, _part, _rest) {
    prev = path;
    _part = _part.replace(/[^A-Za-z_]/g, '');
    if (!top.hasOwnProperty(_part)) {
      if (/\w+/.test(_rest)) { 
        top[_part] = {}; 
        top = top[_part];
      } else {
        top[_part] = val; 
      }
    } else if (!/\w+/.test(_rest)) {
      top[_part] = val;
    } else {
      top = top[_part];
    }
    path = _rest;
  })) && (prev !== path));
});

Substitute yourFormElement with a jQuery expression to get your desired form element.

That iterates over each :input element (form inputs) and then for each loop attempts to break down the "path" of the name using a regular expression, at the same time creating and/or traversing the form data-structure that is being built up. Finally the value of the input is assigned to the leaf node that has been traversed to.

Example of it working: http://jsfiddle.net/8fpLx/10/

That series of conditions inside the while loop could be simplified a lot, but it works.