我有一个这样的表格:

<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"}
    ]
}

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

最佳答案

好的,我知道我的问题是针对特定案例的,但也许这也会对某人有所帮助。我带来了我自己的简单(我认为)解决方案(它在 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"
        }
}

关于javascript - 表单 serializeArray 获取 key :value if key is nested array in HTML?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31162951/

10-11 23:31