HI有几个复选框,其中包含div中的一些属性。假设选中了所有复选框。
<div id="osVersion">
<input type="checkbox" id="chk1" osid="1" versionid="21" />
<input type="checkbox" id="chk2" osid="2" versionid="22" />
<input type="checkbox" id="chk3" osid="2" versionid="11" />
<input type="checkbox" id="chk4" osid="1" versionid="1" />
<input type="checkbox" id="chk5" osid="3" versionid="55" />
<input type="checkbox" id="chk6" osid="2" versionid="45" />
<input type="checkbox" id="chk7" osid="3" versionid="78" />
</div>
我可以将attrs推入像这样的数组
var osVersions = [];
function showOutput() {
$("#osVersion input:checked").each(function (i) {
osVersions.push({ "osid": $(this).attr("osid"), "versionid": $(this).attr("versionid") });
// osVersions.versions.push($(this).attr("versionid"));
});
}
我想创建一个基于osid过滤的json对象,格式如下
{
"osversions" : [
{
"osId" : 1,
"versions" : [21,1]
},{
"osId" : 2,
"versions" : [22,11,45]
},{
"osId" : 3,
"versions" : [55,78]
}
],
"name" : "test",
"xyz":"test"
}
对如何过滤而感到困惑。
答案 0 :(得分:1)
你可以使用像
这样的循环
$('button').click(function() {
var obj = {
"osversions": [],
"name": "test",
"xyz": "test"
},
tmp = {};
$("#osVersion input:checked").each(function() {
var $this = $(this),
osid = $this.attr('osid');
if (!tmp[osid]) {
tmp[osid] = {
"osId": osid,
"versions": []
};
obj.osversions.push(tmp[osid]);
}
tmp[osid].versions.push($this.attr('versionid'))
});
//here obj is a properly formatted object
console.log(obj)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="osVersion">
<input type="checkbox" id="chk1" osid="1" versionid="21" />
<input type="checkbox" id="chk2" osid="2" versionid="22" />
<input type="checkbox" id="chk3" osid="2" versionid="11" />
<input type="checkbox" id="chk4" osid="1" versionid="1" />
<input type="checkbox" id="chk5" osid="3" versionid="55" />
<input type="checkbox" id="chk6" osid="2" versionid="45" />
<input type="checkbox" id="chk7" osid="3" versionid="78" />
</div>
<button>Test</button>
演示:Fiddle