【问题标题】:How to Multi-Filter an Array in Javascript with multiple Conditions from Object?如何使用来自对象的多个条件在 Javascript 中对数组进行多重过滤?
【发布时间】:2022-11-27 18:02:56
【问题描述】:

问候,我正在尝试根据对象的多个条件过滤一系列产品,但我无法理解它。有人可以送我正确的方向吗?

条件(对象)

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

决赛:过滤阵列产品

最终过滤的产品数组应包含具有产品名称的对象微星武士刀&宏基立志,基于给定的条件。有人可以向我解释如何实现这一目标吗?


【问题讨论】:

    标签: javascript reactjs arrays filter


    【解决方案1】:

    您可以迭代所有条件并过滤产品。

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

    【讨论】:

    • 这应该工作!感谢妮娜的快速反应!
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2021-12-24
    • 2022-01-23
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多