【问题标题】:Remove duplicates when appending option to Dropdown将选项附加到下拉菜单时删除重复项
【发布时间】:2020-08-04 23:39:08
【问题描述】:

我已经动态创建了下拉菜单并使用 json 数组中的数据填充它们。

数据:

data = [{hello: 'abc', asd: '123', fgh: '345' }, 
{hello: 'sdf', asd: '456', fgh: 'df' }, 
{hello: 'ty', asd: '789', fgh: '345675' },
{hello: 'qwe', asd: '123', fgh: '987' }]

键数组(用于下拉列表中我需要的数据):arr = ['asd', 'fgh']

创建下拉菜单:

arr.forEach(c => {
   $('div').append(`
     <div class='float-left'>
     <p>${c}</p>
     <select id='${c}'></select>
    </div>`);
});

填充下拉列表:

arr.forEach(o => {
   data.forEach(strs => {
      if (strs[o] != null) {
         $(`#${o}`).append(`<option value='${strs[o]}'>${strs[o]}</option>`);
      }
   });
});

我能够填充下拉列表。如何使用 NO DUPLICATES 填充下拉列表?

【问题讨论】:

    标签: javascript jquery arrays json ecmascript-6


    【解决方案1】:

    您可以为arr 指定的对象索引的每个值创建一个数组,并在使用它添加选项之前对其进行去重。注意我已经结合了你的两个 forEach 循环;这样做需要将id 添加到顶级div。如果您不想这样做,则需要再次将它们分开。

    data = [{hello: 'abc', asd: '123', fgh: '345' }, 
    {hello: 'sdf', asd: '456', fgh: 'df' }, 
    {hello: 'ty', asd: '789', fgh: '345675' },
    {hello: 'qwe', asd: '123', fgh: '987' }]
    
    arr = ['asd', 'fgh']
    
    arr.forEach(o => {
      $('div#top').append(`
         <div class='float-left'>
         <p>${o}</p>
         <select id='${o}'></select>
        </div>`);
      let vals = data.map(strs => strs[o]);
      vals.filter((v, i) => v !== null && vals.indexOf(v) === i)
          .forEach(v => $(`#${o}`).append(`<option value='${v}'>${v}</option>`));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id='top'></div>

    【讨论】:

      【解决方案2】:

      要处理重复的&lt;select&gt; 元素,您不需要附加到通用的“div”选择器。相反,我使用命名类.container

      要处理重复的&lt;option&gt;s,我会使用数组方法.some()

      data = [{hello: 'abc', asd: '123', fgh: '345' }, 
      {hello: 'sdf', asd: '456', fgh: 'df' }, 
      {hello: 'ty', asd: '789', fgh: '345675' },
      {hello: 'qwe', asd: '123', fgh: '987' }]
      
      arr = ['asd', 'fgh']
      
      arr.forEach(c => {
         $('.container').append(`
           <div class='float-left'>
           <p>${c}</p>
           <select id='${c}'></select>
          </div>`);
      });
      
      arr.forEach(o => {
         data.forEach(strs => {
            if (strs[o] != null) {
            
            const alreadyHasThis = $(`#${o} option`).toArray().some(option => option.value === strs[o]);
                        
            if(!alreadyHasThis){
                $(`#${o}`).append(`<option value='${strs[o]}'>${strs[o]}</option>`);
            }
           
            }
         });
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div class="container"></div>

      【讨论】:

        【解决方案3】:

        您可以先对所选数据使用临时数组,然后使用[... new Set(data)] 删除重复项。然后使用这个数组来构建你的控件。

        data = [{hello: 'abc', asd: '123', fgh: '345' }, 
        {hello: 'sdf', asd: '456', fgh: 'df' }, 
        {hello: 'ty', asd: '789', fgh: '345675' },
        {hello: 'qwe', asd: '123', fgh: '987' }]
        
        arr = ['asd', 'fgh']
        
        var selects = arr.reduce((r, e) => (r[e] = [... new Set(data.map(d => d[e]))], r), {});
        
        console.log(selects)
        
        var html = ""
        for (sel of arr) {
          html += `<div class='float-left'>${sel} <select id='${sel}'>`;
          for (data of selects[sel]) 
            html += `<option value='${data}'>${data}</option>`;
          html += `</select></div>`;
        }
        document.querySelector("div").insertAdjacentHTML("beforeend", html);
        &lt;div&gt;&lt;/div&gt;

        参考:How do I convert array of Objects into one Object in JavaScript?https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c

        【讨论】:

          猜你喜欢
          • 2013-02-14
          • 1970-01-01
          • 2013-07-19
          • 2015-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-01
          • 2017-10-19
          相关资源
          最近更新 更多