过滤对象数组,其属性包含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 婆婆高寿祝福语大全简短