过滤对象数组,其任何属性都包含一个值 [英] Filter array of objects whose any properties contains a value

查看:332
本文介绍了过滤对象数组,其任何属性都包含一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是最干净的方法,更好的方法是根据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.

ES6lodash

  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, just for filtering an array with conditions,

Object.keys 获取对象的所有属性名称,

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#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; }

这篇关于过滤对象数组,其任何属性都包含一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆