I have an array of objects like this
[
{
"prop1": "value1",
"prop2": "value1",
"check": {
"gender": ['male'],
"office": ['London','New York']
}
},
{
"prop1": "value2",
"prop2": "value2",
"check": {
"gender": ['female'],
"office": ['Berlin', 'New York']
}
}
]
I want to search this array passing another object, that will be compared to the check property of the array. So, if I search using this object
{
"office": ['New York']
}
I will get back both elements of the above array, but if I search using this one
{
"gender": ['male'],
"office": ['London']
}
this will return the first element only. I want also to be able to pass something like
{
"gender": ['female'],
"office": ['London', 'Berlin'] // <- 2 elements here
}
and get back the second element. I can check if the objects are the same but I don’t know how to do a partial search, how can I do that?
>Solution :
filter()
the data- Check if
every()
key hassome()
value including (includes()
) in the datacheck
array
const data = [{"prop1": "value1", "prop2": "value1", "check": {"gender": ['male'], "office": ['London','New York'] } }, {"prop1": "value2", "prop2": "value2", "check": {"gender": ['female'], "office": ['Berlin', 'New York'] } } ];
const filters = {
"office": ['Berlin']
}
const customFilter = (data, filters) => {
const fKeys = Object.keys(filters);
return data.filter(o =>
fKeys.every(k => (
filters[k].some(fVal =>
o.check[k].includes(fVal)
)
))
);
};
// Without indentations
// return data.filter(o => fKeys.every(k => filters[k].some(fVal => o.check[k].includes(fVal))));
const result = customFilter(data, filters);
console.log(result);