This is a function which filters on multiple object properties and their corresponding arrays.
- I need to match all properties to a pattern and have an array as their property value.
- Properties that match that pattern and contain an array get filtered on whether they contain string values.
The values can be in any one of the arrays related to that object.
All objects which have met the criteria and contain the appropriate strings irrespective of the property array they are contained in. With the exception being that all values are in the same object.
The object containing all string values do not get filtered out.
If I match all object properties containing 'ev_' and those properties contain arrays whose values include 'value75' and '12+'
This should be the resulting output
{
"data": {
"id": 3,
"date": "2019-02-03",
"ev_filter_1": [
"art",
"foodie"
],
"ev_filter_2": [
"value1",
"value75"
],
"ev_filter_3": [
"value1",
"value2"
],
"ev_filter_4": [
"all",
"12+"
]
}
}
From this array of objects
const posts = [{
data: {
id: 1,
date: "2019-02-03",
ev_filter_1: ["art", "foodie"],
ev_filter_2: ["value1", "value2"],
ev_filter_3: ["value1", "value2"],
ev_filter_4: ["all", "12+"]
}
},
{
data: {
id: 2,
date: "",
ev_filter_1: ["arti", "foodie"],
ev_filter_2: ["value1", "value2"],
ev_filter_3: ["value1", "value2"],
ev_filter_4: ["all", "19+"]
}
},
{
data: {
id: 3,
date: "2019-02-03",
ev_filter_1: ["art", "foodie"],
ev_filter_2: ["value1", "value75"],
ev_filter_3: ["value1", "value2"],
ev_filter_4: ["all", "12+"]
}
}
];
This example is currently working but it is ugly and rigid. The "some" is just used for iteration, which I painfully coerced to return true. There is also a nested if statement (horrid).
const posts = [{
data: {
id: 1,
date: "2019-02-03",
ev_filter_1: ["art", "foodie"],
ev_filter_2: ["value1", "value2"],
ev_filter_3: ["value1", "value2"],
ev_filter_4: ["all", "12+"]
}
},
{
data: {
id: 2,
date: "",
ev_filter_1: ["arti", "foodie"],
ev_filter_2: ["value1", "value2"],
ev_filter_3: ["value1", "value2"],
ev_filter_4: ["all", "19+"]
}
},
{
data: {
id: 3,
date: "2019-02-03",
ev_filter_1: ["art", "foodie"],
ev_filter_2: ["value1", "value75"],
ev_filter_3: ["value1", "value2"],
ev_filter_4: ["all", "12+"]
}
}
];
function sift(arrObjLit, pattern, argOne, argTwo) {
return arrObjLit.filter(function(x, y) {
return (result = Object.entries(x).some((q, i) => {
for (let [key, v] of Object.entries(q[1])) {
if (key.startsWith(pattern) && Array.isArray(v) && v.includes(argOne)) {
for (let an of Object.values([x.data][0])) {
if (Array.isArray(an) && an.includes(argTwo)) {
return true;
}
}
}
}
}))
})
}
console.log(...sift(posts, "ev_", "value75", "12+"));
posts
structure be flattened or does everything have to be stored within adata
object? Could there be more/different properties on the object that need to be checked for the filter value? \$\endgroup\${data: {ev_1: ["value75"] }, somethingElse: {ev_2: ["12+"]} }
be matched? \$\endgroup\$