gpt4 book ai didi

javascript - 表单 serializeArray 获取 key :value if key is nested array in HTML?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:42:51 25 4
gpt4 key购买 nike

我有这样一个表格:

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com