Search for a string in all properties of an object in Angular 2

后端 未结 2 981
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 16:59

How to search for a string in all properties of an object in Angular 2 with TS.

I have an array of customers rendered in a table with a search box, if the user ty

相关标签:
2条回答
  • 2021-01-11 17:05

    You can loop over the keys of the item and see if any of them include the string, and return true if any number of them match:

    return items.filter(item =>
      Object.keys(item).some(k => item[k].includes(term.toLowerCase());
    )
    
    0 讨论(0)
  • 2021-01-11 17:12

    You need to apply null check and use .toString() otherwise if value will be number it will not be able to use toLowerCase() method and will raise error.

    return items.filter(item =>
      Object.keys(item).some(
        k =>
          item[k] != null &&
          item[k]
            .toString()
            .toLowerCase()
            .includes(term.toLowerCase())
      )
    );
    
    0 讨论(0)
提交回复
热议问题