How do I add an icon to a custom select2-based ProjectPicker?

Hi all!
I created custom ProjectPicker using select2:

AJS.$("#project-field").auiSelect2();

I filled it in like this:

createOptionsForProjectList: function (projects, $projectPicker) {
     projects.forEach(function (value) {
          var optionHtml = renderOptionsForList({
               id: value.id,
               name: value.fullName,
          });
     $projectPicker.append(optionHtml);
     });
},

Its work well:

image

But I want to get the same display as in Jira with icons:

image

I read the instructions and built a code like this, but it didn’t work:

var state = [
     {
          fullName: "DEV (DEV)",
          iconUrl: "http://localhost:2990/jira/secure/projectavatar?size=xsmall&avatarId=10324",
          id: 10300
     },
     {
          fullName: "Dev2 (DEV2)",
          iconUrl: "http://localhost:2990/jira/secure/projectavatar?size=xsmall&pid=10302&avatarId=10211",
          id: 10302
      }
];


function format(state) {
     if (!state.id) {
          return state.fullName;
     }
     return "<img class='flag' src='" + state.iconUrl + "'/>" + state.fullName;
}


AJS.$("#project-field").auiSelect2({
      formatResult: format(state),
      formatSelection: format(state),
      escapeMarkup: function (m) {
           return m;
      }
});

I can’t figure out what I’m doing wrong. Unfortunately, I haven’t found another solution. But maybe someone has already solved this problem and can help me?

Also, I didn’t understand - how to put projectId in picker? I need it here to get as value.