I'm writing a JSON array filter function based on multiple criteria.
The filter depends on two arrays:
1. The first one contains values that have to be part of searched JSON, and
2. the second contains values that are optional.
I mean to return only the array entries that contain ALL the values from the obligatory array and at least one item from the optional array.
Here's my attempt:
const searchKeys = ['varWord', 'varTrans', 'varSpec'],
obligatory = ['trip', 'pret'],
optional = ['greet', 'lco', 'toto', 'bene'];
function filterByUpdate(obligatory, optional, file) {
return _.filter(file, item => {
return _.some(optional, opt => {
return _.every(obligatory, oblg => {
return _.some(item, value => {
return _.some(searchKeys, n => item[n].toLowerCase().includes(oblg.toLowerCase())) &&
searchKeys.some(n => item[n].toLowerCase().includes(opt.toLowerCase()))
})
});
});
});
}
The code above should only preserve the first entry from the following data array:
[{
"varSpec": "trip",
"varTrans": "pret",
"varWord": "greet",
"stringPol": "group",
"stringDva": "groupGend",
"stringGit": "/tax",
}, {
"varSpec": "trip",
"varTrans": "pret",
"varWord": "friend",
"stringPol": "N",
"stringDva": "N",
"stringGit": "N",
}, {
"varSpec": "group1",
"varTrans": "grp1",
"varWord": "ageGroup1",
"stringPol": "N",
"stringDva": "N",
"stringGit": "N",
}]