I have an array of object arrayOfUsers as below and i want to filter that dynamically based on the object filterValues. If i remove name from filterValues the code should filter the array with age only and if i add id also to filterValues it should filter the array with three properties with out directly specifying key in the filter code and the key should capture from filterValues. I would like to get a solution for this using callback function. Appreciate for the solutions.
const arrayOfUsers = [
{ id: 1, name: 'Sam', age: 33 },
{ id: 2, name: 'Ram', age: 34 },
{ id: 3, name: 'Raj', age: 32 },
{ id: 4, name: 'Som', age: 2 }]
const filterValues = { name: 'R', age: 3 }
Expected Output:
[
{ id: 2, name: 'Ram', age: 34 },
{ id: 3, name: 'Raj', age: 32 }
]
Here is the sample code where i am stuck on.
const test = (arr) => {
Object.keys(filterValues).map((key, i) => arr.filter((user) => user[key].includes(key[i])))
}