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.

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM