var data = [{
"org_name": "General",
"suborg_name": "General1"
}, {
"org_name": "General",
"suborg_name": "General2"
}, {
"org_name": "General",
"suborg_name": "General3"
}, {
"org_name": "Fund",
"suborg_name": "Fund1"
}, {
"org_name": "Fund",
"suborg_name": "Fund2"
}, {
"org_name": "Fund",
"suborg_name": "Fund3"
}]
var tr;
$.each(data, function(i, v) {
tr = $('<tr class="org_name"/>');
tr.append("<td id=''>" + v.org_name + "</td>");
tr.append("<td id=''>" + v.suborg_name + "</td>");
$("table").append(tr);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
</table>
我想要的输出是:
General General1
General2
General3
Fund Fund1
Fund2
Fund3
这怎么可能?
答案 0 :(得分:2)
你可以简单地在循环中建立一个支票。也许与另一个数组/对象进行比较。
var data = [{
"org_name": "General",
"suborg_name": "General1"
}, {
"org_name": "General",
"suborg_name": "General2"
}, {
"org_name": "General",
"suborg_name": "General3"
}, {
"org_name": "Fund",
"suborg_name": "Fund1"
}, {
"org_name": "Fund",
"suborg_name": "Fund2"
}, {
"org_name": "Fund",
"suborg_name": "Fund3"
}];
var added = [];
$.each(data, function(i, v) {
var name = " ";
if( added.indexOf(v.org_name) == -1 ) {
name = v.org_name;
added.push(v.org_name);
}
var tr = $('<tr class="org_name"/>');
tr.append("<td id=''>" + name + "</td>");
tr.append("<td id=''>" + v.suborg_name + "</td>");
$("table").append(tr);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
</table>
&#13;
答案 1 :(得分:1)
点击此处jsfiddle
var tr;
var orgName=' ';
$.each(data, function(i, v) {
if(orgName!=v.org_name){
tr = $('<tr class="org_name"/>');
tr.append("<td id=''>" + v.org_name + "</td>");
tr.append("<td id=''>" + v.suborg_name + "</td>");
}else{
tr = $('<tr class="org_name"/>');
tr.append("<td id=''> </td>");
tr.append("<td id=''>" + v.suborg_name + "</td>");
}
orgName = v.org_name;
$("table").append(tr);
})
答案 2 :(得分:1)
查找是否存在具有组织名称的现有tr。如果存在,则将空字符串放在第一个td中,并在相同的org tr之后追加。如果没有,则在第一个td中添加组织名称并附加到表。
var data = [{
"org_name": "General",
"suborg_name": "General1"
}, {
"org_name": "General",
"suborg_name": "General2"
}, {
"org_name": "General",
"suborg_name": "General3"
}, {
"org_name": "Fund",
"suborg_name": "Fund1"
}, {
"org_name": "Fund",
"suborg_name": "Fund2"
}, {
"org_name": "Fund",
"suborg_name": "Fund3"
}]
var tr;
$.each(data, function(i, v) {
var rowExist = $('table').find('tr.' + v.org_name).length;
tr = $('<tr class="org_name ' + v.org_name + '"/>');
var orgName = '';
if (rowExist == 0)
{
orgName = v.org_name;
$('table').append(tr);
}
else
{
$('table').find('tr.' + v.org_name).last().after(tr);
}
tr.append("<td id=''>" + orgName + "</td>");
tr.append("<td id=''>" + v.suborg_name + "</td>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
</table>