我收到此值
[ { "name": "sname", "value": "Agency" }, { "name": "pincode", "value": "110031" }, { "name": "add", "value": "Agency IX/6242, 1st Floor, h Mohaa No.1, nehru Gali, Near Sanatan Dh, Gand, " }, { "name": "city", "value": "Delhi" }, { "name": "state", "value": "Delhi" }, { "name": "country", "value": "India" }, { "name": "phone", "value": "9990" }, { "name": "email", "value": "a@gmail.com" }
但我希望如下所示
seller": {"name": "Walter White","pincode": "400005","address": "abc, xyz","city": "Mumbai","state": "Maharashtra","country": "India","phone": "99999999999","email": "walter.white @test.com"},
我的代码是
form id="myFormvama" method="POST">
<label>Seller Name</label><input type="text" name="sname" value=""><br>
<label>Pincode</label><input type="text" name="pincode" value=""><br>
<label>Address</label><input type="text" name="add" value=""><br>
<label>City</label><input type="text" name="city" value=""><br>
<label>State</label><input type="text" name="state" value=""><br>
<label>Country</label><input type="text" name="country" value=""><br>
<label>Phone</label><input type="text" name="phone" value=""><br>
<label>Email</label><input type="text" name="email" value=""><br>
<input type="submit" name="submit" value="Send Request" id="submit">
</form>
<script>
var formData = JSON.stringify($("#myFormvama").serializeArray());
document.write(formData);
</script>
请有人建议我使用片段,以便在json中获得正确的值。
答案 0 :(得分:0)
您可以使用Array#reduce:
创建一个新对象var formData = JSON.stringify($("#myFormvama").serializeArray());
formData = formData.reduce(function (obj, next) {
obj.seller[next.name] = next.value;
return obj;
}, { seller: {} });