【问题标题】:Filter array of array within a complex object and return that object过滤复杂对象中的数组数组并返回该对象
【发布时间】:2021-12-12 22:58:39
【问题描述】:

我试过这样写管道:

这是我需要达到的目标

过滤器将允许隐藏不包含所选颜色 (res/FilterMenuDataModel) 的任何对象 (items/ItemModel[])

选定颜色均值的colorIds 数组。

 transform(items: ItemModel[]): Observable<ItemModel[]> {
    return this.menuElementsDataService.filterMenuFinalDataChanged$.pipe(
      map((res) => {
        if (!res) {
          return items;
        }

        return filter(items, (i) => 'need your help here';
      })
    );
  }

item.model.ts

export interface ItemModel {
  itemId?: number;
  itemName?: string;
  colorIds?: number[]; // one array is this
}

filter-menu-data-model.ts

export interface FilterMenuDataModel {
 
  colorIds?: number[]; // the other array is this
}

注意:res 对象具有FilterMenuDataModel 属性。

我已经尝试了很多事情/很多小时,但没有任何运气。你知道怎么做吗?我在这里使用了Lodash。但是 Javascript 方式也很好,因此我可以稍后将其转换为 Lodash。

【问题讨论】:

    标签: javascript angular typescript ionic-framework lodash


    【解决方案1】:

    我想我理解的目的是找到与 filterMenu 选择的项目没有共同颜色 ID 的项目。 Lodash 提供intersection(),所以过滤谓词可以是一个空交集的测试,如下...

    const items = [
      { itemId: 0, itemName: 'zero', colorIds: [32, 33, 34] },
      { itemId: 1, itemName: 'one', colorIds: [33, 34, 35] },
      { itemId: 2, itemName: 'two', colorIds: [34, 35, 36] },
    ];
    
    // only item one above does not include colors 32 and 36
    const filterMenuData = { colorIds: [32, 36] };
    
    const hideTheseItems = items.filter(item => {
      return _.intersection(item.colorIds, filterMenuData.colorIds).length === 0;
    });
    console.log(hideTheseItems);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2021-02-26
      • 2017-10-07
      相关资源
      最近更新 更多