HTML:如何將表單數組轉換爲JavaScript中的JSON? (對象數組)?
<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"
理想情況下,我正在尋找解決方案如何做到這一點,以及爲了學習的邏輯。
http://stackoverflow.com/questions/10356370/convert-array-of-json-object-strings-to-array-of-js-objects檢查此鏈接 – Nicholas
會做,謝謝! – ZZPLKF