篩選屬性中包含 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 次瀏覽

助力你的職業

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.