简体   繁体   English

如何使用 Object 中的多个条件对 Javascript 中的数组进行多重过滤?

[英]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.您好,我正在尝试根据来自 object 的多个条件过滤一系列产品,但我无法理解它。 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.根据给定条件,最终过滤的产品数组应包含产品名称为Msi KatanaAcer Aspire的对象。 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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