Home > Mobile >  how to filter a array of object by another object as key in JS?
how to filter a array of object by another object as key in JS?

Time:04-13

I have an array of objects

let allData = [
  {title:"Adams",age:24,gender:"male"},
  {title:"Baker",age:24,gender:"female"},
  {title:"Clark",age:23,gender:"male"},
  {title:"Davis",age:23,gender:"female"},
  {title:"Ghosh",age:23,gender:"female"},
  {title:"Adams",age:23,gender:"male"},
  {title:"Irwin",age:25,gender:"male"},
]

and list of filter in a Object like this

let filters = {
  title:{filterTerm:[]},
  gender:{filterTerm:["male"]},
  age:{filterTerm:[23]}
}

i want to apply multiple filters on top of allData i tried using Array.some with Array.includes but it is not working when with multiple filters items below is my code

const getFilterRows = (rows, filters) => {
    let filterCols = Object.keys(filters)
    if (filterCols.length == 0) {
        return rows
    }
    else {
        let filteredR = rows.filter(i => {
            return filterCols.some((s) => {
                return filters[s].filterTerm.includes(i[s])
            })
        });
        return filteredR
    }
}
let filterd = getFilterRows(allData,filters)

expected output

[  
 {title:"Clark",age:23,gender:"male"},
 {title:"Adams",age:23,gender:"male"},
]

CodePudding user response:

You could map each key from filters and filter allData based on if filterTerm includes the item being searched, ignoring the filter if filterTerm is empty. Below example would also allow you to add more items to filterTerm if needed.

let allData = [
  {title:"Adams",age:24,gender:"male"},
  {title:"Baker",age:24,gender:"female"},
  {title:"Clark",age:23,gender:"male"},
  {title:"Davis",age:23,gender:"female"},
  {title:"Ghosh",age:23,gender:"female"},
  {title:"Adams",age:23,gender:"male"},
  {title:"Irwin",age:25,gender:"male"}
]

let filters = {
  title:{filterTerm:[]},
  gender:{filterTerm:["male"]},
  age:{filterTerm:[23]},
}

const getFilterRows = (rows, filters) => {
  return rows.filter(row => (
    Object.keys(filters)
      .map(key => filters[key].filterTerm.length ? filters[key].filterTerm.includes(row[key]) : true)
      .every(Boolean))
  )
 }

let filtered = getFilterRows(allData,filters)

console.log(filtered)

  • Related