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

需要将带有方括号的字段名称转换为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" } } } }

我想将包含方括号的字段名称转换为JavaScript中的对象。 我已经看到PHP确实将它们转换为一个数组但是在JavaScript中没有看到一个,尽管已经搜索了几天。 p>

数据: p>

 &lt; input name =“address [permanent] [name]”type =“text”value =“My Address”&gt; 
&lt; input name =“address [permanent] [street] [street_one]  “type =”text“value =”My Street One“&gt; 
&lt; input name =”address [permanent] [street] [street_two]“type =”text“value =”My Street Two“&gt; 
   pre> 
 
 

结果(我想要实现的目标): p>

  form = {address:{permanent:{name:“My 地址“,街道:{street_one:”My Street One“,street_two:”My Street Two“}}}} 
  code>  pre> 
  div>

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.