篩選屬性中包含 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' }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP