过滤对象数组,其属性包含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 送给学长毕业祝福语简短