gpt4 book ai didi

javascript - 如何在 Javascript 中将表单数组转换为 JSON? (对象数组)?

转载 作者:行者123 更新时间:2023-12-01 07:06:25 25 4
gpt4 key购买 nike

HTML:

<form id="products">
<tbody id="product-list">
<tr>
<td><input type="hidden" name="type[]" value="jackets">jackets</td>
<td><input type="hidden" name="name[]" value="test1">test1</td>
<td><input type="hidden" name="color[]" value="red">red</td><td>
<input type="hidden" name="size[]" value="S">S</td>
</tr>
<tr>
<td><input type="hidden" name="type[]" value="jackets">jackets</td>
<td><input type="hidden" name="name[]" value="test2">test2</td>
<td><input type="hidden" name="color[]" value="blue">blue</td>
<td><input type="hidden" name="size[]" value="S">S</td>
</tr>
</tbody>
</form>

JS:

JSON.stringify($("#products").serializeArray();

输出:

[{"name":"type[]","value":"jackets"},{"name":"name[]","value":"test1"},{"name":"color[]","value":"red"},{"name":"size[]","value":"S"},{"name":"type[]","value":"jackets"},{"name":"name[]","value":"test2"},{"name":"color[]","value":"blue"},{"name":"size[]","value":"S"}]

期望的输出:

对象数组,就像这样(只是视觉效果)

Object[0].type -> "jackets"
Object[0].name -> "test1"
Object[0].color -> "red"
Object[0].size -> "S"
Object[1].type -> "jackets"
Object[1].name -> "test2"
Object[1].color -> "blue"
Object[1].size -> "S"

理想情况下,我正在寻找如何做到这一点的解决方案,以及学习的逻辑。

最佳答案

您可以使用Array.prototype.map()在每个对象中添加与您要查找的值相对应的键:

var arr = [{"name":"type[]","value":"jackets"},{"name":"name[]","value":"test1"},{"name":"color[]","value":"red"},{"name":"size[]","value":"S"},{"name":"type[]","value":"jackets"},{"name":"name[]","value":"test2"},{"name":"color[]","value":"blue"},{"name":"size[]","value":"S"}];

var result = arr.map(function(elem){
elem[elem.name.replace(/\W/g, '')] = elem.value; //adds key "type" with value "jackets"
return elem;
});

result[0].jackets //"jackets"

关于javascript - 如何在 Javascript 中将表单数组转换为 JSON? (对象数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564784/

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