如何将表单字段动态转换为多维js对象? [英] How would I dynamically convert form fields to multi-dimensional js object?

查看:62
本文介绍了如何将表单字段动态转换为多维js对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将一组输入动态转换为多维对象以传入ajax调用。

I'm struggling to dynamically convert a set of inputs into a multi-dimensional object for passing in an ajax call.

假设我有一个Person,有多个地址。
我的字段目前如下所示:

Assume I have a Person, with multiple Addresses. My fields currently look like this:

<input name='Person[name]' value='Bradley'/>
<input name='Person[addresses][home]' value='123 Anywhere Drive.'/>
<input name='Person[addresses][work]' value='456 anywhere Road.'/>

如何将我的字段转换为如下所示的ab对象:

How would one convert my fields into ab object that looks like this:

Person :
{
    name: 'Bradley',
    addresses:
    {
        home: '123 Anywhere Drive.',
        work: '456 anywhere Road.'
    }
}

我需要动态地执行此操作(函数需要在提供的输入时工作)并在N深度工作。

I need to do this dynamically (function needs to work regardless of the inputs provided) and work at N-depth.

(注意:jQuery可用)。

(Note: jQuery available).

推荐答案

http://jsfiddle.net/w4Wqh/1/

老实说,我认为在正则表达式中有一种方法可以做到这一点..但是我无法理解。所以,这是一个丑陋的字符串操作。无论哪种方式,我认为这应该让你走上正确的轨道:

Honestly I think there's a way to do this in a regex.. but I couldn't figure it out. So, it's a bit of ugly string manipulation. Either way, this should get you on the right track I think:

function serialize () {
    var serialized = {};
    $("[name]").each(function () {
        var name = $(this).attr('name');
        var value = $(this).val();

        var nameBits = name.split('[');
        var previousRef = serialized;
        for(var i = 0, l = nameBits.length; i < l;  i++) {
            var nameBit = nameBits[i].replace(']', '');
            if(!previousRef[nameBit]) {
                previousRef[nameBit] = {};
            }
            if(i != nameBits.length - 1) {
                previousRef = previousRef[nameBit];
            } else if(i == nameBits.length - 1) {
                previousRef[nameBit] = value;
            }
        }
    });
    return serialized;
}

console.log(serialize());

快速解释。这只是用'name'属性抓取任何东西,然后迭代它们。对于每次迭代,它都会抓取名称并将其拆分为[。这基本上可以让您了解物品放置的距离。所以,对于Person [地址] [工作],你会得到Person,地址],工作]。

Quick explanation. This just grabs anything with a 'name' attribute, and then iterates over them. For each iteration, it grabs the name and splits it on '['. This gets you basically how far into the object you need to put things. So, for Person[addresses][work], you would get Person, addresses], work].

然后,有一个棘手的部分。由于对象总是通过引用传递,我们可以看到序列化变量中是否包含Person。如果没有,它会添加它,并将值设置为空对象..它通用,足以用于存储更多内容,或者在必要时替换。如果没有我们需要经历的更多级别,它只需要获取元素的值并将其分配给它具有的引用。否则,代码会抓取对其刚刚创建的内容的引用,并再次循环,执行相同的操作。所以,对于Person [地址] [工作] ..

Then, there's the tricky part. Since objects are always passed around by reference, we can see if the serialized variable has 'Person' in it. If not, it adds it, and sets the value to an empty object.. which is generic enough to be used for storing more things, or replaced if necessary. If there are no more levels that we need to go through, it just takes the value of the element and assigns it to the reference it has. Otherwise, the code grabs a reference to whatever it just made, and loops again, performing the same operation. So, for Person[addresses][work]..


  1. serialized.Person是否存在?编号设置serialized.Person到{}。这不是循环的结束,将对serialized.Person的引用存储为previousRef。

  2. previousRef.addresses是否存在? (serialized.Person.addresses)编号。将previousRef.addresses设置为{}。这不是循环的结束,将previousRef.addresses存储引用为previousRef。

  3. previousRef.work是否存在? (serialized.Person.addresses.work)编号。将previousRef.work设置为{}。 <强>等待即可。这是循环的结束。将previousRef.work设置为元素中的值。

  1. Does serialized.Person exist? No. Setting serialized.Person to {}. This is not the end of the loop, store reference to serialized.Person as previousRef.
  2. Does previousRef.addresses exist? (serialized.Person.addresses) No. Setting previousRef.addresses to {}. This is not the end of the loop, store reference to previousRef.addresses as previousRef.
  3. Does previousRef.work exist? (serialized.Person.addresses.work) No. Setting previousRef.work to {}. Wait. This is the end of the loop. Setting previousRef.work to the value in the element.

这篇关于如何将表单字段动态转换为多维js对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆