如何基于另一个对象数组过滤对象数组?

时间:2019-05-13 11:04:35

标签: javascript arrays reactjs object filter

我有如下两个对象数组

conditions= [
          {
            'condition': 'Expert',
            'value': 'All'
          },
          {
            'condition': 'Coach',
            'value': 'willaim'
          },
          {
            'condition': 'manager',
            'value': 'Brandy Lovings'
          },
          {
            'condition': 'site',
            'value': 'ALL'
          },
          {
            'condition': 'client',
            'value': 'ALL'
          }
        ]

data=[
{
          "Date": "11/6/2018",
          "client": "Verizon",
          "Expert": "Ellison, Lauren",
          "Coach": "willaim",
          "manager": "Brandy Lovings",
          "site": "Sundance",
          "Metric": "STR"
        },
{
          "Date": "11/6/2018",
          "client": "Amzaon",
          "Expert": "Ellison, Lauren",
          "Coach": "Dash Williamson",
          "manager": "David",
          "site": "abc",
          "Metric": "STR"
        }
]

我想用conditions数组过滤数据数组,就像如果conditions数组中的condition属性包含Expert,那么我需要基于data.Expert = conditions[Expert Conditionindex].value过滤数据数组,那么我需要返回所有带有此conditions的数据。 / p>

另一件事是,如果value: 'ALL'则不需要在特定条件下进行过滤。

所需的输出类似于

filteredData = [
{
              "Date": "11/6/2018",
              "client": "Verizon",
              "Expert": "Ellison, Lauren",
              "Coach": "willaim",
              "manager": "Brandy Lovings",
              "site": "Sundance",
              "Metric": "STR"
            }
]

如何解决此问题?

2 个答案:

答案 0 :(得分:2)

您可以使用不带ALL标志的条件子集进行过滤。

var conditions = [{ condition: "Expert", value: "All" }, { condition: "Coach", value: "willaim" }, { condition: "manager", value: "Brandy Lovings" }, { condition: "site", value: "ALL" }, { condition: "client", value: "ALL" }],
    data = [{ Date: "11/6/2018", client: "Verizon", Expert: "Ellison, Lauren", Coach: "willaim", manager: "Brandy Lovings", site: "Sundance", Metric: "STR" }, { Date: "11/6/2018", client: "Amzaon", Expert: "Ellison, Lauren", Coach: "Dash Williamson", manager: "David", site: "abc", Metric: "STR" }],
    filters = conditions.filter(({ value }) => value.toUpperCase() !== 'ALL'),
    result = data.filter(o =>
        filters.every(({ condition, value }) => o[condition] === value));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

这应该为您工作:

    const conditionsObj={}

    conditions.filter(({value})=>value.toLowerCase()!=='all').forEach((condition)=>{
          conditionsObj[condition.condition]=condition.value
        })



     const results=data.filter((item)=>{
              let match=false;  
             Object.keys(conditionsObj).forEach((_key)=>{
                if(conditionsObj[_key]===item[_key]){
                  match=true;
                }
              })
              return match;
            })

console.log(results)