问题描述
我想知道什么是最干净的方法,更好的方法是根据string keyword
过滤对象数组.搜索必须在对象的任何属性中进行.
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
!
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.
使用的方法:
Object.keys
for getting all property names of the object,
Array#some
for iterating the keys and exit loop if found,
String#toLowerCase
获取可比较的值,
String#toLowerCase
for getting comparable values,
String#includes
检查两个字符串(如果一个包含另一个字符串).
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; }
这篇关于过滤对象数组,其任何属性都包含一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!