简体   繁体   English

Lodash 过滤对象中的所有值

[英]Lodash filter through all values in a object

I'm using Lodash to filter an object.我正在使用 Lodash 过滤对象。

var search = 180;
var filterBy = "other_num";

var items = [{
  id: 1,
  name: 'Fulano da Silva 1',
  num: 300,
  other_num: 183,
  date: '05/04/2018'
}, {
  id: 2,
  name: 'Amanda',
  num: 250,
  other_num: 180,
  date: '12/03/2018'
}, {
  id: 3,
  name: 'Fulano da Silva 3',
  num: 300,
  other_num: 211,
  date: '02/03/2018'
}, {
  id: 4,
  name: 'Fulano da Silva 4',
  num: 300,
  other_num: 211,
  date: '02/03/2018'
}, ];

var filtered = _.filter(items, function(item) {
  return (item[filterBy].toString().toLowerCase().indexOf( search.toString().toLowerCase()) > -1);
});

console.log(filtered);

As you can see, I've setted search and filterBy vars.如您所见,我已经设置了searchfilterBy变量。 But instead of "filter by" some key, I was wondering if it's possible to find the value of search in any key.但不是“过滤”某个键,我想知道是否有可能在任何键中找到search的值。

Something like this:像这样的东西:

var filtered = _.filter(items, function(item) {
  return (item.id.toString().toLowerCase().indexOf(search.toString().toLowerCase()) > -1) || (item.name.toString().toLowerCase().indexOf(search.toString().toLowerCase()) > -1) || (item.num.toString().toLowerCase().indexOf(search.toString().toLowerCase()) > -1) || (item.other_num.toString().toLowerCase().indexOf(search.toString().toLowerCase()) > -1) || (item.date.toString().toLowerCase().indexOf(search.toString().toLowerCase()) > -1);
});

Although the code above works (see this fiddle and check the console), it's not dynamic nor reusable.尽管上面代码有效(请参阅此小提琴并检查控制台),但它不是动态的,也不是可重用的。 I mean, if it's needed to add/remove keys, I would have to manually add/remove directives from the return .我的意思是,如果需要添加/删除键,我将不得不从return手动添加/删除指令。

Any thoughts on how to make this smarter and reusable ?关于如何使这个更智能可重用的任何想法? Am I missing some Lodash functionality?我是否缺少一些 Lodash 功能?

Thanks in advance :)提前致谢 :)

But instead of "filter by" some key, I was wondering if it's possible to find the value of search in any key .但不是“过滤”某个键,我想知道是否有可能在任何键中找到 search 的值。

Vanilla JS solution - try Object.values Vanilla JS 解决方案- 尝试Object.values

var search = 180;
var output = items.filter( s => Object.values( s ).includes( search ) );

Demo演示

 var search = 180; var items = [{ id: 180, //changed for the purpose of testing name: 'Fulano da Silva 1', num: 300, other_num: 183, date: '05/04/2018' }, { id: 2, name: 'Amanda', num: 250, other_num: 180, date: '12/03/2018' }, { id: 3, name: 'Fulano da Silva 3', num: 300, other_num: 211, date: '02/03/2018' }, { id: 4, name: 'Fulano da Silva 4', num: 300, other_num: 211, date: '02/03/2018' }]; var output = items.filter( s => Object.values( s ).includes( search ) ); console.log( output );

怎么样(es6):

_.filter(items, { [filterBy]: search });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM