首页 > 解决方案 > 如何通过数组的数组内的属性过滤数组

问题描述

我试图establishments通过是否在数组本身specialCategories的数组中找到来过滤数组中的每个建立。establishmentSpecialsestablishments

我可以establishmentSpecials为每个机构过滤阵列,但我想保留机构部分,如图所示。

            //masterEstablishments array is from the db

            //The categories array, to filter out all but the following
            specialCategories = ["Breakfast Special"];

            //The array to hold the filtered establishments
            var establishments;

            //For all Establishments
            for(var i=0;i<masterEstablishments.length;i++){
                //Filter out Catorgory from establishmentSpecials where Category is not found in specialCategories
                establishments = masterEstablishments[i].establishmentSpecials.filter(x => specialCategories.includes(x.Category));
            }

            console.log("Filtered establishments");
            console.log(establishments);

总而言之,例如

        var establishments = [ {address: "55 Garden rd"},
            [{Category: "Breakfast Special"}, {Category: "Dinner Special"}]
          ];

应该成为

        establishments = [ {address: "55 Garden rd"},
            [{Category: "Breakfast Special"}]
          ];

因为“晚餐特价”不在特殊类别中

specialCategory = [{Category: "Breakfast Special"}]

非常感谢。

在此处输入图像描述

标签: javascriptarraysfilter

解决方案


您是说您只是想删除场所中的{Category: "Dinner Special"}?

        specialCategories = ["Breakfast Special"];

        const establishments = establishments.map((element) => {
          return {
            Cuisine_Type: element.Cuisine_type,
            Address: element.Address, // add the other properties so on and so forth
            establishmentSpecials : element.establishmentSpecials.map((ES_element) =>{
              if (ES_element.Category === specialCategories[0]) {
                return ES_element;
              }                  
            })});

推荐阅读