简体   繁体   中英

How to create a multi-filter function to filter out multiple attributes?

I have an array of objects to be filtered:

[
  {
    "name": "Apple",
    "age": 24,
    "model": "Android",
    "status": "Under development",
  },

  {
    "name": "Roboto",
    "age": 24,
    "model": "Apple",
    "status": "Running",
  },
  
  .
  .
  .
  .

]  

I need to filter the array using multiple parameters using JavaScript's filter method. I have got a partial solution but could not get the expected output.

The filter should also work with multiple values for a single attribute. Eg, age=54,23 or model="Android","Apple" etc.

I'm trying to mimic the working of filters just like that of an e-commerce site, where we can compare all of a product's attributes and customer's chosen tags to output a filtered list of products.

If you format your filter conditions just like an object in your data array, but with values being arrays of possible values, then you can use the filter method as follows:

 let data = [ { "name": "Apple", "age": 24, "model": "Android", "status": "Under development", }, { "name": "Roboto", "age": 24, "model": "Apple", "status": "Running", }, { "name": "Samsung", "age": 26, "model": "Blueberry", "status": "Running", }, ]; let filter = { "name": ["Roboto", "Ericsson"], "age": [22, 24, 26], }; let res = data.filter(obj => Object.entries(filter).every(([prop, find]) => find.includes(obj[prop]))); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM