首页 > 解决方案 > 仅当对象位于两个数组中时才会选择 select 中的选项

问题描述

我需要进行多项选择并显示所有节点,但只检查 2 个数组中的节点。

我在前端使用 Angular 8 和 TypeScript。

private mountSelect(nodesInRelation, lineApiKey) {
    console.log(nodesInRelation, lineApiKey);

    // if (nodesInRelation)

    let select = document.getElementById(lineApiKey);

     for (let node of this.allNodes) {
       for(let nodeInRelation of nodesInRelation) {
         if (node.name == nodeInRelation.name) {
           let newoption = new Option(node.name, node.apikey, null, true);
           (select as HTMLSelectElement).add(newoption);
           break;
         } else {
                  let newoption = new Option(node.name, node.apikey, null, false);
                  (select as HTMLSelectElement).add(newoption);
         }
       }

     }
M.updateTextFields();
    M.AutoInit();
  }

但我得到重复的条目。

    <tr *ngFor="let communityLine of communityLines">
      <td>{{communityLine.name}}</td>
      <td>{{communityLine.instrument.name}}</td>
      <td>{{communityLine.param.name}}</td>
      <td>{{communityLine.contextSource.name}}</td>
      <td>{{communityLine.sampleType.name}}</td>
      <td>{{communityLine.value}}</td>
      <td>
        <select multiple [id] ="communityLine.apiKey">
        </select>
      </td>

我怎样才能有效地做到这一点?

谢谢大家

标签: javascripthtmlangulartypescript

解决方案


必须获得更大的图片才能获得正确的细节,但我会像这样重写该代码:

let nodeNames nodesInRelation.map(node => node.name);

let filteredNodes = this.allNodes.filter(function(node){
   return nodeNames.includes(node.name); // Use a polyfill for IE support
});
//I would set all nodes to false to prevent any weird issues
this.allNodes.forEach(node => {
           let newoption = new Option(node.name, node.apikey, null, false);
           (select as HTMLSelectElement).add(newoption);
});
//then set only selected ones
filteredNodes.forEach(node => {
           let newoption = new Option(node.name, node.apikey, null, true);
           (select as HTMLSelectElement).add(newoption);
});

推荐阅读