I want to filter objects based on a set of arrays containing filter terms. It basically works until one of the filter arrays contains multiple terms. Here is the code:
// the filters const filters = { "eyeColor": ["blue"], "gender": ["male"], "age": ["33"], "tags": ["d3js", "vuejs"] // multiple terms in the filter array breaks the code (returns empty array) } // the data const users = [ { "age": "33", "eyeColor": "blue", "tags": "d3js, max, grotesk", "gender": "male", }, { "age": "31", "eyeColor": "blue", "tags": "vuejs, adrian, serif", "gender": "male", }, { "age": "37", "eyeColor": "brown", "tags": "vuejs, max, mono, d3js", "gender": "female", }, { "age": "33", "eyeColor": "blue", "tags": "vuejs, markus, grotesk", "gender": "male", }, ] // the filter function let results = users.filter(function (object) { return Object.entries(filters).every(function ([key, value]) { return value.every(function (filter) { return object[key].includes(filter) }) }) }); console.log(results);
I get an empty array, while the expected result would be:
{
"age": "33",
"eyeColor": "blue",
"tags": "d3js, max, grotesk",
"gender": "male",
},
{
"age": "33",
"eyeColor": "blue",
"tags": "vuejs, markus, grotesk",
"gender": "male",
}
How can I get the expected result?
The code uses
return value.every(function (filter) ...
// ^^^^^
but you don't want to match all of the tags in the permitted array, only some
( any ):
return value.some(function (filter) ...
// ^^^^
Here's a demonstration:
const filters = { "eyeColor": ["blue"], "gender": ["male"], "age": ["33"], "tags": ["d3js", "vuejs"] } const users = [{ "age": "33", "eyeColor": "blue", "tags": "d3js, max, grotesk", "gender": "male", }, { "age": "31", "eyeColor": "blue", "tags": "vuejs, adrian, serif", "gender": "male", }, { "age": "37", "eyeColor": "brown", "tags": "vuejs, max, mono, d3js", "gender": "female", }, { "age": "33", "eyeColor": "blue", "tags": "vuejs, markus, grotesk", "gender": "male", }, ]; const filterEntries = Object.entries(filters); const results = users.filter(user => filterEntries.every(([key, permitted]) => permitted.some(e => user[key].includes(e)) ) ); console.log(results);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.