I have an array of objects with order details:
let filteredOrders = []; // output array
let orders = [
{
id: 1,
name: "ORDER 1",
material: "8756"
},
{
id: 2,
name: "ORDER 2",
material: "4548"
},
{
id: 3,
name: "ORDER 3",
material: "8756"
},
{
id: 4,
name: "ORDER 4",
material: "5678"
}
]
And filters in another object:
let filters = {
materials: {
selected: ""
},
ids: {
selected: ""
}
}
At some point in the program, one or both filters receive a value and I have to filter the array if value is not empty "" and not "all".
For example:
filters.materials.selected = "8756";
Expected output:
filteredOrders = [
{
id: 1,
name: "ORDER 1",
material: "8756"
},
{
id: 3,
name: "ORDER 3",
material: "8756"
}
]
Or:
filters.materials.selected = "8756";
filters.ids.selected = 3;
Expected output:
filteredOrders = [
{
id: 3,
name: "ORDER 3",
material: "8756"
}
]
Filter has to be dynamic. No specifiying of "keys".
What I have tried:
for (var [key, value] of Object.entries(filters)) {
filteredOrders = orders.filter(function(order) {
if (filters[key].selected !== "all" && filters[key].selected !== "") {
if (order[key.slice(0, -1)] == filters[key].selected) {
console.error("ADD", order, order[key.slice(0, -1)], filters[key].selected);
return order;
}
}
});
}
// EMPTY
if (filteredOrders.length < 1) filteredOrders = orders;
The output is really strange though, by:
filters.materials.selected = "8756";
filters.ids.selected = 3;
The filteredOrders array has 3 Orders -> ids: 2, 3, 3 (duplicate "3")
2
Answers
If your filter has the same name as your search field, this would be easier.
Then you can do it like below:
Try this.