'How to filter an array of object using a dynamic object?
I have this array of object:
data = [
{
delivered: 118989,
sent: 132288,
undelivered: 13299,
_id: {
broker: "123",
campaign: "notificacao1",
category: "teste",
event_code: "21295",
priority: "HIGH",
}
},
{
delivered: 27,
sent: 35,
undelivered: 8,
_id: {
broker: "555",
campaign: null,
category: "teste",
event_code: "4494",
priority: "HIGH",
}
}
]
and I have an Object witch can be dynamic, with one or more property, like this:
filterForm = {
broker: "123",
}
or
filterForm = {
broker: "123"
priority: "HIGH"
}
I want to filter the array of object, using the result of the second dynamic object.
Note that I need to filter inside the property _id
I tried using filter.
this.data = this.data.filter(function (item) {
for (var key in filterForm) {
if (item[key] === undefined || item[key] != filterForm[key])
return false;
}
return true;
});
but I always get false
Solution 1:[1]
You could use a filter function filtering array by using a loop on dynamic object (in my example is called filterObj):
let myArray = [ { delivered: 118989, sent: 132288, undelivered: 13299, _id: { broker: "123", campaign: "notificacao1", category: "teste", event_code: "21295", priority: "HIGH", } }, { delivered: 27, sent: 35, undelivered: 8, _id: { broker: "555", campaign: null, category: "teste", event_code: "4494", priority: "HIGH", } } ];
let filterObj = {broker: "123", priority: "HIGH"};
let result = myArray.filter(el => {
for (const [key, value] of Object.entries(filterObj)) {
return el._id[key] === value;
}
});
console.log(result)
Solution 2:[2]
this.data = this.data.filter((item) => Object
.entries(filterForm)
.every(([key, value]) => item._id[key] === value)
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giovanni Esposito |
| Solution 2 | Florat |
