Brownman Revival Brownman Revival - 3 months ago 7
jQuery Question

Append tr but dont append if already added in tr



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>





The output i want is

General General1
General2
General3
Fund Fund1
Fund2
Fund3


How is this possible?

Answer

You can simply build yourself a check in the loop. Maybe with another array/object to compare with.

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 = "&nbsp;";

  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);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
</table>