在 JavaScript 中过滤属性包含值的对象数组
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的对象数组 −
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' } ]