dpjpo746884 2013-08-16 06:38
浏览 34
已采纳

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

1条回答 默认 最新

  • douke1905 2013-08-16 06:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集