【问题标题】:Filtering List using a drop-down selection value in javascript使用javascript中的下拉选择值过滤列表
【发布时间】:2019-05-19 02:44:38
【问题描述】:

我有一个对象数组。根据下拉值的选择过滤对象数组。

const itemsList=[{
"id":"123",
"problems":{
    "causes":[ 
         {
        "SSEnabled": true,
        "IndusEnabled": false,
        "LogEnabled": true
        }
    ]
}
},
{
"id":"234",
"problems":{
    "causes":[
          {
        "SSEnabled": false,
        "IndusEnabled": false,
        "LogEnabled": true
        }
    ]
}
}]

我们有一个下拉菜单来过滤 SSEnabled 原因。下拉选项有“show”、“nofilter”、“exclude”。

需要根据下拉选择过滤列表。

如果选择了“SSEnabled”下拉菜单的“show”选项,则“SSEnabled”:“true”的列表项应该是结果。(即;id:“123”)

如果选择“SSEnabled”原因的“排除”,则“SSEnabled:false”应为结果的列表项。(即;id:“234”)

如果选择“nofilter”,它应该忽略过滤器。 (即;id:“123”,id:“234”)

filterList(filterType, filterValue, itemsList) {
   // filterType : SSEnabled (type of dropdown changed)
   //filterValue : show, exclude , no filter
itemsList.map((items) => {
  if (
    items &&
    items.problems &&
    items.problems.causes &&
    items.problems.causes.length
  ) {
    items.problems.causes.filter((cause) => {
       if (cause[filterType] === true && filterValue === 'show') {
        return true;
      }
      if (cause[filterType] === false && filterValue === 'exclude') {
        return true;
      }
    });
  }
});

console.log(itemsList, 'filtered List');
}

但是列表没有被过滤。请帮忙过滤。

【问题讨论】:

  • 使用数组过滤方式
  • 那么在你的 map 方法中你没有返回任何东西
  • Array.map 是错误的工具。 Array.map 适用于您想要一个包含与输入数组一样多的元素的输出数组。

标签: javascript arrays json object filter


【解决方案1】:

一个干净的方法是定义实现逻辑的函数查找,然后将正确的函数传递给some()(或find())。您可以将其传递给field,例如showexclude,以及您想要过滤的key,例如SSEnabled

const itemsList=[{"id":"123","problems":{"causes":[ {"SSEnabled": true,"IndusEnabled": false,"LogEnabled": true}]}},{"id":"234","problems":{"causes":[{"SSEnabled": false,"IndusEnabled": false,"LogEnabled": true}]}}]

// implement the selection logic based on keyword
// will return items where some of the cause match the condition
const filters = (field, key ) => {
    let options = {
     show:     (i) => i[key] == true,
     nofilter: (i) => true,
     exclude:  (i) => i[key] == false
    } 
    return options[field]
}

// filter using the above function:

let SSEnabled = itemsList.filter(item => item.problems.causes.some(filters('show', 'SSEnabled')) )
console.log(SSEnabled)

let SS_not_enabled = itemsList.filter(item => item.problems.causes.some(filters('exclude', 'SSEnabled')) )
console.log(SS_not_enabled)

let LogEnabled = itemsList.filter(item => item.problems.causes.some(filters('show', 'SSEnabled')) )
console.log(LogEnabled)

【讨论】:

  • 过滤器对象中的 SSEnabled 可以是动态的吗?因为我有更多这样的属性要过滤,比如“indusEnabled”、“logisticsEnabled”。
  • @user8599269,确定不是简单的对象查找,而是使其成为一个获取您正在查找的属性的函数。见编辑。
猜你喜欢
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
相关资源
最近更新 更多