Greeting, I'm trying to filter an array of products based on multiple conditions from an object and i can't get my head around it. Can someone send me in the right direction?
Conditions (Object)
const Conditionobject = {
Brand: ["msi", "acer"]
Processor: ["intel i7", "intel i9"]
Refreshrate: ["165 hz"]
}
Products (Array)
const AllProducts= [
{
Productname: Acer Nitro,
Specifications: { Brand: "acer", Processor: "intel i7", Refreshrate: "144 hz"}
},
{
Productname: Msi Katana,
Specifications: { Brand: "msi", Processor: "intel i7", Refreshrate: "165 hz"}
},
{
Productname: Acer Aspire,
Specifications: { Brand: "acer", Processor: "intel i9", Refreshrate: "165 hz"}
},
]
Final: Filtered Array Products
The final filtered array of products should contain the objects with the productnames Msi Katana & Acer Aspire, based on the given conditions. Can someone explain me how to achieve this?
CodePudding user response:
You could iterate all conditions and filter the products.
const
conditions = { Brand: ["msi", "acer"], Processor: ["intel i7", "intel i9"], Refreshrate: ["165 hz"] },
products = [{ Productname: "Acer Nitro", Specifications: { Brand: "acer", Processor: "intel i7", Refreshrate: "144 hz" } }, { Productname: "Msi Katana", Specifications: { Brand: "msi", Processor: "intel i7", Refreshrate: "165 hz" } }, { Productname: "Acer Aspire", Specifications: { Brand: "acer", Processor: "intel i9", Refreshrate: "165 hz" } }],
result = products.filter(product => Object
.entries(conditions)
.every(([key, values]) => values.includes(product.Specifications[key]))
)
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }