How to get exact word using angular filter pipe and not words matching the value?

陌路散爱 提交于 2019-12-13 03:30:55

问题


Example if i search [App] i don't want to see [Apple, Appliance, Appliances], instead i want to only see [App] in the search

    @Pipe({
    name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any, filter: any, isAnd: bool): any {
    if (filter && Array.isArray(items)) {
      let filterKeys = Object.keys(filter);
      if (isAnd) {
        return items.filter(item =>
            filterKeys.reduce((memo, keyName) =>
                (memo && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] === "", true));
      } else {
        return items.filter(item => {
          return filterKeys.some((keyName) => {
            console.log(keyName);
            return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === "";
          });
        });
      }
    } else {
      return items;
    }
  }
}

回答1:


Instead of doing new RegExp(filter[keyName], 'gi').test(item[keyName])), you will need to do filter[keyName] === item[keyName]. I hope this helps




回答2:


I think with this code is success

export class FilterPipe implements PipeTransform {
  transform(items: any, filter: any, isAnd: bool): any {
    if (filter && Array.isArray(items)) {
      return filter.map(filterItem => items.filter(itemItem => itemItem === filterItem).join())
    } else {
      return items;
    }
  }
}


来源:https://stackoverflow.com/questions/57700936/how-to-get-exact-word-using-angular-filter-pipe-and-not-words-matching-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!