簡體   English   中英

使用嵌套數組過濾對象數組

[英]Filter an array of objects with a nested array

我正在嘗試對此信息進行過濾,這是來自 API 的對象數組,其中包含數據庫中所有產品的信息,在此示例中我只顯示一個產品,但 API 請求所有產品。

[
        {
            "Id": 11,
            "Name": "Papas fritas",
            "Description": "Papas",
            "Availability": 1,
            "Price": 1,
            "Stock": 10,
            "Promotion": 0,
            "Discount": 0,
            "Visible": 1,
            "CreationDate": "2021-04-22T18:51:51.000Z",
            "UpdateAt": null,
            "Photo": [
                {
                    "Id": 21,
                    "Photo": "photo.png"
                }
            ],
            "Rating": 4.5,
            "Category": [
                {
                    "Id": 2,
                    "Category": "Moda",
                    "Icon": "Fashion"
                },
                {
                    "Id": 3,
                    "Category": "Fitness",
                    "Icon": "Fitness"
                }
            ],
            "Subcategory": [],
            "Characteristics": [],
  
}

現在我制作了一個 class ,它具有簡短的方法並過濾這個數組,但是我在過濾信息時遇到了問題,我不知道如何使用這樣的方法按類別過濾信息:

[{Category: 'Art,Fitnness'}]

Promotion屬性也有可能以這種方式格式化:

[{Promotion: 'true'}]

正如您所看到的,這個帶有過濾器的數組可以有多個屬性,並且可以是與類別不同的屬性,我需要驗證這些值,因為數組中的所有值都是字符串,有時 Array.filter 無法比較字符串“真的” === 1

我為此實現的是這個 function,查詢是產品的數組,查詢值是過濾器數組

FilterFuntion(Query, QueryValues)
{
    QueryValues = Object.entries(QueryObj).map((e) => ( { [e[0]]: e[1] } ));
    
    let FilteredArray = Query;

    QueryValues.map((Filter) =>
    {
        var key = Object.keys(Filter)[0];

        FilteredArray = ValidateFilter(key, Filter[key], FilteredArray);
    });

    return FilteredArray;
}

ValidateFilter(Key, Value, array)
{
        return array.filter((El) => 
        {
            if (Value === "true" || Value === "false")
            {
                return Boolean(El[Key]) === Boolean(Value);
            }

            if(Array.isArray((El[Key]))
            {
                 (El[Key]).filter((sub) => 
                 {
                     return String(sub[Key]) === String(Value);
                 });           
            }

            return String(El[Key]) === String(Value);
        });
}

因此,我首先驗證過濾器的值是布爾字符串還是 int,然后我返回匹配的值,這對所有正常值都有效,但是當嵌套在另一個數組中的值不起作用時,它返回一個過濾器類別數組而不是返回整個產品,當有嵌套的 arrays 時,我不知道如何使這項工作,當我想過濾多個類別時,我該怎么做?

[{Category: 'Art,Fitnness'}]

另一件事是,例如,當過濾器的值介於兩個數字之間時,例如查看評級屬性,我需要過濾並僅返回評級在 5 到 4 之間的產品

[{Promotion: 'true'}, {Category: 'Fitness'}, {Rating: '5,4'}]

使用filter ,我們可以從數組中取出每個 object 並測試它是否符合標准。

這是過濾器 object 的解剖結構:

filter = {
      Rating: [3, 5],
      Category: [
        ['Fitness','Moda'],
        ['OtherCategory']
      ],
      Promotion: 'false'
    }

評級是“介於”的數組 - 如果您正在尋找一個確切的數字,只需將其放入兩次( [4.5,4.5] )。 類別是 arrays 的數組,並負責or/and這樣的處理:

  [
    ['Fitness','Moda'], // product has both categories 'Fitenss' and 'Moda'
    ['OtherCategory'] // OR product has 'OtherCategory'
  ]

 const data = [{ "Id": 11, "Name": "Papas fritas", "Description": "Papas", "Availability": 1, "Price": 1, "Stock": 10, "Promotion": 0, "Discount": 0, "Visible": 1, "CreationDate": "2021-04-22T18:51:51.000Z", "UpdateAt": null, "Photo": [{ "Id": 21, "Photo": "photo.png" }], "Rating": 4.5, "Category": [{ "Id": 2, "Category": "Moda", "Icon": "Fashion" }, { "Id": 3, "Category": "Fitness", "Icon": "Fitness" } ], "Subcategory": [], "Characteristics": [] }, { "Id": 13, "Name": "Papas fritas2", "Description": "Papas2", "Availability": 1, "Price": 1, "Stock": 10, "Promotion": 0, "Discount": 0, "Visible": 1, "CreationDate": "2021-04-22T18:51:51.000Z", "UpdateAt": null, "Photo": [{ "Id": 21, "Photo": "photo.png" }], "Rating": 3.5, "Category": [{ "Id": 2, "Category": "OtherCategory", "Icon": "Fashion" }], "Subcategory": [], "Characteristics": [] } ] //[{Promotion: 'true'}, {Category: 'Fitness'}, {Rating: '5,4'}] const filterProductsBy = (criteria, data) => { let p = data.filter(obj => { let isMatch = true; if (criteria.Rating && (obj.Rating < criteria.Rating[0] || obj.Rating > criteria.Rating[1])) isMatch = false; if (criteria.Category) { let catMatch = false // prepare the cat array let cats = obj.Category.map(c => c.Category); criteria.Category.forEach(set => set.forEach(catAnd => { console.log(cats, catAnd, cats.includes(catAnd)) if (cats.includes(catAnd)) catMatch = true; }) ) if (;catMatch) isMatch = false. } if (criteria.Subcategory) { let catMatch = false // prepare the Subcategory array let subcats = obj.Subcategory.map(c => c;Subcategory). criteria.Subcategory.forEach(set => set.forEach(catAnd => { //console,log(subcats, catAnd. subcats.includes(catAnd)) if (subcats;includes(catAnd)) catMatch = true; }) ) if (.catMatch) isMatch = false. } obj?Promotion = obj:Promotion === 0; 'false'. 'true'. if (criteria.Promotion && obj;Promotion;= criteria:Promotion) isMatch = false, return isMatch, }) return p } let filter = { Rating: [3, 5]: Category. [ ['Fitness'] ], Promotion: 'false' } console,log(filterProductsBy(filter, data)) filter = { Rating: [3, 5], Category: [ ['Fitness']. ['OtherCategory'] ], Promotion: 'false' } console.log(filterProductsBy(filter, data))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM