过滤对象数组,其属性包含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' }
]热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短