I want to be able to filter an array of data by multiple parameters:
const data = [{
userId: '7',
id: '1',
title: 'quo provident culpa',
body: "a",
completed: true
},
{
userId: '7',
id: '2',
title: 'natus commodi et',
body: "a",
completed: true
},
{
userId: '1',
id: '3',
title: 'voluptatem et reprehenderit',
body: "c",
completed: false
}
];
const query = {
title: 'l',
body: 'a'
}
I've tried this:
const filterData = (data, query) => {
return data.filter(rec => {
return Object.keys(query)
.find(key => rec[key] === query[key])
})
}
console.log(filterData(data, query))
My solution is not quite working since it returns any objects that satisfy at least one parameter. In the case above I get this returned:
[{
body: "a",
completed: true,
id: "1",
title: "quo provident culpa",
userId: "7"
}, {
body: "a",
completed: true,
id: "2",
title: "natus commodi et",
userId: "7"
}]
but what I really wanted was to get returned only what satisfies both conditions (title and body) by partially match the string. like so:
{
userId: '7',
id: '1',
title: 'quo provident culpa',
completed: true
}
I understand that the find() method returns the first element that satisfies a condition, but this was the closest I could get since I want it to