Currently, I am faced with the task of filtering an array of objects based on criteria from another array. Essentially, I am looking to refine a list based on filters selected by the user.
To illustrate, let's consider my initial list of results:
[
{uuid: 1, type: 2, style: 3, somethingelse: 4, anotherval: 5}
{uuid: 2, type: 4, style: 4, somethingelse: 4, anotherval: 5}
{uuid: 3, type: 6, style: 4, somethingelse: 4, anotherval: 5}
{uuid: 4, type: 9, style: 2, somethingelse: 4, anotherval: 5}
{uuid: 5, type: 1, style: 2, somethingelse: 4, anotherval: 5}
....
]
The filter list that I need to apply is dynamic, meaning it can contain various key-value pairs chosen by the user. This filter list might look like this:
[
{key: 'type', value: '2'},
{key: 'style', value: '4'}
]
My goal is to generate a filtered list that only includes values matching all the specified key-value pairs.
I've explored multiple solutions on Stack Overflow but haven't had success yet. Some resources I've referred to include:
How to check if a value exists in an object using JavaScript
How to efficiently check if a Key Value pair exists in a Javascript "dictionary" object
lodash: filter array of objects with a different array of objects
Filtering for Multiple Fields in Object Array in Javascript/Lodash - Stack Overflow
Despite these references, I'm yet to find a solution that meets my requirements.
Here is a snippet of what I've attempted so far:
...
// In this section, I convert the filters into an array format {key: '', value: ''} as mentioned earlier. This step is not mandatory, and I can remove it if necessary.
// Initially, my filters are in this format: {type: 2, style: 4}
const filterArr = Object.keys(cleanedFilters).map(key => ({ key, value: cleanedFilters[key] }))
const result = flatten(
map(filterArr, function (fil) {
return filter(searchResults, function (a) {
return a.hasOwnProperty(fil.key) && a[fil.key] === parseInt(fil.value)
})
})
)
The output of this code block produces an array containing certain objects:
[
{
"uuid": 1,
"type": 2,
"style": 3,
"somethingelse": "4",
"anotherval": 5
},
{
"uuid": 2,
"type": 4,
"style": 4,
"somethingelse": "4",
"anotherval": 5
},
{
"uuid": 3,
"type": 6,
"style": 4,
"somethingelse": "4",
"anotherval": 5
}
]
This outcome includes items satisfying both style = 4
and type = 2
. However, my desired result is an empty array since there are no entries with style 4 and type 2
.
As shown in the provided example, I am open to utilizing lodash or similar libraries if necessary.
I appreciate any suggestions or insights you may have. Thank you in advance.