簡體   English   中英

如何使用 Object 中的多個條件對 Javascript 中的數組進行多重過濾?

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

您好,我正在嘗試根據來自 object 的多個條件過濾一系列產品,但我無法理解它。 有人可以送我正確的方向嗎?

條件(對象)

const Conditionobject = {
Brand: ["msi", "acer"]
Processor: ["intel i7", "intel i9"]
Refreshrate: ["165 hz"]
}

產品(數組)

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"}
},
]

決賽:過濾陣列產品

根據給定條件,最終過濾的產品數組應包含產品名稱為Msi KatanaAcer Aspire的對象。 有人可以向我解釋如何實現這一目標嗎?


您可以迭代所有條件並過濾產品。

 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