简体   繁体   中英

How to Multi-Filter an Array in Javascript with multiple Conditions from Object?

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?


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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM