Is it possible to filter array values by multiple values by using underscore?

北慕城南 提交于 2019-12-21 04:11:13

问题


I have the following array of values:

[
   {
     id: 1,
     field: 'map'
   },
   {
     id: 2,
     field: 'dog'
   },
   {
     id: 3,
     field: 'map'
   }
]

I need to find out elements with field equals dog and map. I know I could use the _.filter method and pass an iterator function, but what I want to know is whether or not there's a better solution to this issue where I could pass search field and possible values. Could someone provide a better way of doing so?

EDIT::

I could use the following approach:

_.where(array, {field: 'dog'})

But here I may check only one clause


回答1:


_.filter(data, function(item){ return item.field === 'map' || item.field === 'dog'; })

If you want to create a function which accepts field and values it can look like this:

function filter(data, field, values) {
    _.filter(data, function(item){ return _.contains(values, item[field]); })
}



回答2:


Just pass your filter criteria as the third parameter of _.filter(list, predicate, [context]) which is then set as the context (this) of the iterator:

var data = [
  { id: 1, field: 'map'   },
  { id: 2, field: 'dog'   },
  { id: 3, field: 'blubb' }
];

var filtered = _.filter(
  data,
  function(i) { return this.values.indexOf(i.field) > -1; },
  { "values": ["map", "dog"] } /* "context" with values to look for */
);

console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


来源:https://stackoverflow.com/questions/19476067/is-it-possible-to-filter-array-values-by-multiple-values-by-using-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!