pok*_*ken 1 javascript jquery json
我需要从具有相同名称参数的多个字段的表单中创建一个JSON,但我想将其分组为数组?可能吗?
编辑:我尝试了建议的解决方案,但我不能将name的值用作新数组中的键...你可以帮我解决一下如何将其更改为{name:value []}而不是{name: name,value:value []}?
var json = JSON.stringify($("#frm").serializeArray());
$("#json").html(json);
var myArray = $("#frm").serializeArray();
var groups = {};
for (var i = 0; i < myArray.length; i++) {
var groupName = myArray[i].name;
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(myArray[i].value);
}
myArray = [];
for (var groupName in groups) {
myArray.push({name: groupName, value: groups[groupName]});
}
var json = JSON.stringify(myArray);
$("#json").html(json);
var myArray2 = [];
for (var groupName in groups) {
myArray2.push({groupName: groups[groupName]});
}
var json2 = JSON.stringify(myArray2);
$("#json2").html(json2);Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form id="frm">
<input type="text" name="a" value="1"/>
<input type="text" name="b" value="2"/>
<input type="text" name="a" value="3"/>
<input type="text" name="b" value="4"/>
</form>
<br/>
Edited: I followed the suggested solution, its like this now:
<p id="json">
</p>
<br/>
but I can't use the value of "name" as key for the array
<p id="json2">
</p>
<br/>
<br/>
is it possible to make it like this instead?
<br/>
<p>
{"a":[1,3], "b":[2,4]}
</p>Run Code Online (Sandbox Code Playgroud)
您可以object通过循环form数据来创建新的
const json = $("#frm").serializeArray();
const Obj = {};
json.forEach((item) => (!Obj[item.name]) ? Obj[item.name] = [item.value] : Obj[item.name].push(item.value))
$("#json").html(JSON.stringify(Obj));Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<form id="frm">
<input type="text" name="a" value="4"/>
<input type="text" name="b" value="1"/>
<input type="text" name="a" value="2"/>
<input type="text" name="b" value="3"/>
</form>
<br/>
<p id="json">
</p>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |