The code below uses only βselectβ as the jquery selector, so it will affect all selected cells on the page. You might want to change this.
The code below also does not handle one of the selected options, which you probably should follow.
var type = [{"Id":1,"Name":"This is a name"}]; var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"}]; var output = []; $.each(type, function(){ //for each type add an optgroup output.push('<optgroup label="'+this.Name+'">'); var curId = this.Id; //linear search subTypes array for matching ParentId $.each(subType, function(k,v){ if( this.ParentId = curId ){ output.push('<option label="'+this.Name +'" value="'+ this.Id +'">'+ this.Name +'</option>'); //DELETE the element from subType array so the next search takes less time subType.splice(k,1); } }); output.push('</optgroup>'); }); //change the 'select' here to the id of your selectbox $('select').html(output.join(''));
source share