【问题标题】:How can I make a Search String to search like an IN filter on an Array of Object如何使搜索字符串像对象数组上的 IN 过滤器一样进行搜索
【发布时间】:2020-05-20 09:19:01
【问题描述】:

用户界面上的过滤器允许用户使用 IN 标准进行搜索。然后搜索字符串将成为条件对象的属性。 搜索字符串看起来像"1234,5436,8765",然后condition Object 看起来像```

condition: {
     field: "Id",
     operator: "in",
     value: "1234,5436,8765"
}

现在因为这将是 IN 过滤器,所以我应该使用 whar 标准,以便像来自 results Array 的 IN 标准一样进行值搜索。

例如对于 like 过滤器,我将设置我的 value 属性像这样%1234% 以便在结果数组中搜索它。

【问题讨论】:

标签: javascript arrays filter


【解决方案1】:

您的问题不清楚,因此请尝试对其进行编辑以使其更清楚。

我在回答中做了一个很大的假设(因为问题并不清楚):

您可以使用 switch 语句,然后为每种情况使用各种过滤方法。

你可以做得更稳健,但在问题更清楚之前,构建这个解决方案没有多大意义。

const myArrOfObs = [
    {Id: 1234, title: "some title 1", other: "some other val 1"},
    {Id: 2468, title: "some title 2", other: "some other val 2"},
    {Id: 8240, title: "some title 3", other: "some other val 3"},
    {Id: 9371, title: "some title 4", other: "some other val 4"},
    {Id: 5436, title: "some title 5", other: "some other val 5"},
    {Id: 8365, title: "some title 6", other: "some other val 6"},
    {Id: 8765, title: "some title 7", other: "some other val 7"},
    {Id: 3946, title: "some title 8", other: "some other val 8"}
];

const condition = {
     field: "Id",
     operator: "in",
     value: "1234,5436,8765"
};

function filterArr(arr, cond) {
  switch (cond.operator){
    case "in":
      const valueArr = cond.value.split(',');
      return arr.filter(item => valueArr.includes(item[cond.field].toString()));
    //case "like":
      //return arr.filter( ... );
    default:
      return null;  
  }    
}

const myFilteredArr = filterArr(myArrOfObs, condition);

console.log(myFilteredArr);

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 2018-06-21
    • 1970-01-01
    • 2021-12-16
    • 2019-09-17
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多