任何属性都包含值的对象的过滤器数组 [英] Filter array of objects whose any properties contains a value
问题描述
我想知道根据 string 关键字
过滤对象数组的最简洁、更好的方法是什么.必须在对象的任何属性中进行搜索.
I'm wondering what is the cleanest way, better way to filter an array of objects depending on a string keyword
. The search has to be made in any properties of the object.
当我输入 lea
时,我想遍历所有对象及其所有属性以返回包含 lea
When I type lea
I want to go trough all the objects and all their properties to return the objects that contain lea
当我输入 italy
时,我想遍历所有对象及其所有属性以返回包含 italy
的对象.
When I type italy
I want to go trough all the objects and all their properties to return the objects that contain italy
.
我知道有很多解决方案,但到目前为止我只看到了一些您需要指定要匹配的属性.
I know there are lot of solutions but so far I just saw some for which you need to specify the property you want to match.
欢迎使用 ES6 和 lodash!
ES6 and lodash are welcome!
const arrayOfObject = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}, ];
filterByValue(arrayOfObject, 'lea') // => [{name: 'Lea',country: 'Italy'}]
filterByValue(arrayOfObject, 'ita') // => [{name: 'Lea',country: 'Italy'}, {name: 'John',country: 'Italy'}]
推荐答案
您可以对其进行过滤并仅搜索搜索字符串中出现的一次.
You could filter it and search just for one occurence of the search string.
使用的方法:
Array#filter
,只用于过滤带条件的数组,
Array#filter
, just for filtering an array with conditions,
对象.键
用于获取对象的所有属性名称,
Object.keys
for getting all property names of the object,
Array#some
用于迭代键并在找到时退出循环,
Array#some
for iterating the keys and exit loop if found,
String#toLowerCase
用于获取可比较的值,
String#toLowerCase
for getting comparable values,
String#包括
用于检查两个字符串,如果一个包含另一个.
String#includes
for checking two string, if one contains the other.
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}
const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];
console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于任何属性都包含值的对象的过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!