userName
userName

Reputation: 945

How to set up flexible data filtering?

I accept data about users and a condition for filtering and sorting from a JSON file. I need to create a flexible filtering system for several parameters at once. There are two filtering rules - "include" and "exclude". That is, users with certain parameters will be removed, or vice versa. How can I create a flexible filtering system? Now I wrote a condition for checking for rules and I don’t know how to implement flexible filtering.

User data:

"data": [{
    "user": "user1",
    "city": "New York",
    "disabled": false
  },
  {
    "user": "user2",
    "rating": "New York",
    "disabled": true
  },
  {
    "user": "user3",
    "rating": "London",
    "disabled": true
  }
],

Filtration conditions:

"condition": {
  "exclude": [{
    "disabled": true
  }],
}

//or

"condition": {
  "include": [{
      "city": "London"
    },
    {
      "disabled": true
    },
  ],
}

//or both

"condition": {
  "include": [{
    "city": "New York"
  }],
  "exclude": [{
    "disabled": true
  }],
}

Upvotes: 0

Views: 55

Answers (1)

Nairi Abgaryan
Nairi Abgaryan

Reputation: 666

I made minor changes in the condition object, but I am sure you can adapt this in your code. Here is one way to filter with a few conditions.

var data = [
   {
    "user": "user1",
    "city": "New York",
    "disabled": false
  },
  {
    "user": "user2",
    "city": "New York",
    "disabled": false
  },
  {
    "user": "user3",
    "city": "London",
    "disabled": true
  }
]

var condition = {
  "include": {
    "city": "New York",
    "disabled": false
  },
  "exclude": {
     "user": "user2",
  },
}

function advancedFilter(data, condition){
    return data.filter(item => {
        var cond = true
        for(var key in condition.include){
           cond = cond && item[key] === condition.include[key] 
        }

        for(var key in condition.exclude){
           cond = cond && item[key] !== condition.exclude[key] 
        }

       return cond
    })
}

var result = advancedFilter(data, condition)
console.log(result)

Upvotes: 2

Related Questions