筛选属性中包含 JavaScript 值的对象数组


假设,我们有一个这样的对象数组 −

const arr = [{
   name: 'Paul',
   country: 'Canada',
}, {
   name: 'Lea',
   country: 'Italy',
}, {
   name: 'John',
   country: 'Italy',
}, ];

我们需要设计一种方法来根据字符串关键字筛选对象数组。需要在对象的任何属性中进行搜索。

例如 −

When we type "lea", we want to go through all the objects and all their properties to return the objects that contain "lea".
When we type "italy", we want to go through all the objects and all their properties to return the objects that contain italy.

示例

由此生成的代码为 −

const arr = [{
      name: 'Paul',
      country: 'Canada',
   }, {
      name: 'Lea',
      country: 'Italy',
   }, {
      name: 'John',
      country: 'Italy',
}, ];
const filterByValue = (arr = [], query = '') => {
   const reg = new RegExp(query,'i');
   return arr.filter((item)=>{
      let flag = false;
      for(prop in item){
         if(reg.test(item[prop])){
            flag = true;
         }
      };
      return flag;
   });
};
console.log(filterByValue(arr, 'ita'));

输出

控制台中的输出为 −

[
   { name: 'Lea', country: 'Italy' },
   { name: 'John', country: 'Italy' }
]

更新于: 20-11-2020

839 次浏览

助力你的职业

完成课程以获得认证

立即开始
广告