I have an array of objects
const Data = [
{first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer'},
{first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'engineer'},
{first_name: 'Cindy', city_name: 'Tokyo', age: 32, designation: 'influencer'},
{first_name: 'Barn', city_name: 'sydney', age: 34, designation: 'lawyer'},
{first_name: 'Yolanda', city_name: 'Seoul', age: 32, designation: 'chef'},
{first_name: 'Mike', city_name: 'London', age: 42, designation: 'bartender'},
{first_name: 'Olivia', city_name: 'LA', age: 34, designation: 'officer'}
]
I also have an object containing filters
const Filters = {
first_name: ['Ammy', 'Dave', 'Mike'],
city_name: ['LA'],
age: [22, 34]
}
I have to filter the data so that all the filters are applied and it should be an and condition. For the above Data and Filters only the row containing Ammy
should be displayed. The challenging part is that the filters can have only one key or all keys. Filters can be just { first_name: ['Dave']}
I tried writing some code but it will not apply all the filters
const newData = [];
Object.entries(Filters).map(([filter, Values]) => {
const filteredData = Data.filter(item => {
if (Values.find( value => value === item[filter])) {
newData.push(item);
}
});
})
lucky is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Mapping the Object.entries()
of filters
won’t get you your desired result, you need to filter()
your data
array.
What you can do is for each object in data (ie: person
), check if every
key from filters has value from its array as a value in the current person
object you’re looking at (using .some()
). If it does, then you can return true
keeping the object in the final array:
const data = [{ first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer' }, { first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'engineer' }, { first_name: 'Cindy', city_name: 'Tokyo', age: 32, designation: 'influencer' }, { first_name: 'Barn', city_name: 'sydney', age: 34, designation: 'lawyer' }, { first_name: 'Yolanda', city_name: 'Seoul', age: 32, designation: 'chef' }, { first_name: 'Mike', city_name: 'London', age: 42, designation: 'bartender' }, { first_name: 'Olivia', city_name: 'LA', age: 34, designation: 'officer' } ];
const filters = { first_name: ['Ammy', 'Dave', 'Mike'], city_name: ['LA'], age: [22, 34] };
const filterEntires = Object.entries(filters)
const res = data.filter(person => filterEntires.every(
([key, values]) => values.some(val => val === person[key])
));
console.log(res);