过滤对象数组,其属性包含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 春节福字祝福语简短