如何在JavaScript中有效地将对象数组与另一个数组进行比较?

时间:2017-12-27 10:13:33

标签: javascript arrays typescript ecmascript-6

我有一个函数,我必须返回一个带匹配过滤器的元素数组。这是功能代码:

filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) {
   let tempFilterArray = [];
   let masterFilterList = getMasterFilterList();
   /*
   filterNameToSearch can be a string either as `Item2` or `Item3`

   masterFilterList will be of type
   masterFilterList: Array<any> = [
   {
      Item1: 'some-item-1',
      Item2: 'some-item-2',
      Item3: 'some-item-3',
      Item4: 'some-item-5',
   },
   {
      Item1: 'some-item-10',
      Item2: 'some-item-11',
      Item3: 'some-item-12',
      Item4: 'some-item-13',
   },......
  ];  

  appliedFilters will be of type
  appliedFilters: Array<any> = [
   {
      name: 'Item1',
      filters: [
          {value: 'some-item-1', status: 'selected'},
          {value: 'some-item-10', status: 'selected'}
      ]
   },......
  ];  
 */

 for (let masterFilterItem of masterFilterList) {
   //Missing logic here
 }
}

我想过滤masterFilterList以返回一系列项目 filterNameToSearch = 'Item2'在以下条件下:

1)对于appliedFilterItem中的每个数组元素(假设appliedFilters),将appliedFilterItem.namemasterFilterItem[appliedFilterItem.name]进行比较,并检查appliedFilterItem中是否有任何过滤器与masterFilterItem[appliedFilterItem.name]

相同的值

2)条件必须类似于masterFilterItem[appliedFilterItem[0].name] == appliedFilterItem[0].filters[0].value && appliedFilterItem[0].filters[0].status === 'selected' && masterFilterItem[appliedFilterItem[1].name] == appliedFilterItem[1].filters[0].value && appliedFilterItem[1].filters[0].status === 'selected' and so on for all appliedFilterItems。但appliedFilters中的元素数量是动态的。

那么请帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

  return masterFilterList.map(el => el[filterNameToSearch])
      .filter(value => 
         appliedFilters.some(({name, filters}) =>
            name === filterNameToSearch &&
            filters.some(filter => 
              filter.status === "selected" &&
              filter.value === value
            )
         )
      );