表单serializeArray get key:value如果key是HTML中的嵌套数组?

时间:2015-07-01 13:35:13

标签: javascript jquery

我有一个这样的表格:

<select name="dog[0][name]">...</select>
<select name="dog[0][color]">...</select>
<select name="dog[0][height]">...</select>
<select name="dog[0][weight]">...</select>

<select name="dog[1][name]">...</select>
<select name="dog[1][color]">...</select>
<select name="dog[1][height]">...</select>
<select name="dog[1][weight]">...</select>
...

现在,如果我在此调用$('form').serializeArray();,则输出如下:

[
    {
        name: "dog[0][name]",
        value: "ABC"
    },
    {
        name: "dog[0][color]",
        value: "Blue"
    },
    {
        name: "dog[0][height]",
        value: "41"
    },
    {
         name: "dog[0][weight]",
        value: "10"
    },
    {
        name: "dog[1][name]",
        value: "XYZ"
    },
    {
        name: "dog[1][color]",
        value: "Pink"
    },
    {
        name: "dog[1][height]",
        value: "27"
    },
    {
        name: "dog[1][weight]",
        value: "7"
    },
    // ...
]

我怎样才能这样:

{
    dog: [
        0: {"name": "ABC", "color": "Blue", "height": 41, "weight": "10"}
        1: {"name": "XYZ", "color": "Pink", "height": 27, "weight": "7"}
    ]
}

?有没有一种方法不需要嵌套循环?

1 个答案:

答案 0 :(得分:0)

好的,我知道我的问题是针对具体案例的,但也许这对某些人也有帮助。我带着我自己的简单(我认为)解决方案(它在coffeescript中):

values = $('form').serializeArray()

model = {}
for val in values
    matches = val.name.match /dog\[(.*)\]\[(.*)\]/
    model[matches[1]] = {} if !model[matches[1]]
    model[matches[1]][matches[2]] = val.value
console.log model

转换为纯JS应该是:

var values = $('form').serializeArray();

var model = {};
for (var i = 0, var len = values.length; i < len; i++) {
    var val = values[i];
    var matches = val.name.match(/dog\[(.*)\]\[(.*)\]/);
    if (!model[matches[1]]) {
        model[matches[1]] = {};
    }
    model[matches[1]][matches[2]] = val.value;
}
console.log(model);

生成此输出:

{
    0:
        {
            "name": "ABC",
            "color": "Blue",
            "height": "41",
            "weight": "10"
        }
    1:
        {
            "name": "XYZ",
            "color": "Pink",
            "height": "27",
            "weight": "7"
        }
}