简体   繁体   English

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

[英]need to convert field name with square brackets into a javascript object

I would like to convert a field name consisting of square brackets into an object in JavaScript. 我想将由方括号组成的字段名称转换为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. 我已经看到PHP确实将它们转换为数组但是在JavaScript中没有看到过,尽管已经搜索了几天。

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. 用jQuery表达式替换yourFormElement以获取所需的表单元素。

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. 迭代每个:input元素(表单输入)然后为每个循环尝试使用正则表达式分解名称的“路径”,同时创建和/或遍历正在构建的form数据结构起来。 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/ 工作示例: http//jsfiddle.net/8fpLx/10/

That series of conditions inside the while loop could be simplified a lot , but it works. while循环中的一系列条件可以简化很多 ,但它可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM