lodash _.filter可选择基于数组的条件?

时间:2018-04-10 20:59:00

标签: javascript filter lodash

_.filter函数适用于包含单个项目的对象作为值。

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']

// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']

有没有办法将相同的函数应用于具有数组作为值的对象?

我想得到任何可能包含该值的元素,包括它是否是数组的值之一:

var users = [
  { 'user': 'barney', 'age': 36, 'active': true, 'colors': ['blue', 'yellow'] },
  { 'user': 'fred',   'age': 40, 'active': false, 'colors': ['blue', 'purple'] }
  { 'user': 'mary',   'age': 40, 'active': false, 'colors': ['blue', 'grey'] }
];

_.filter(users, { 'colors': 'blue' });
// => all objects as they all contain 'blue'

_.filter(users, { 'active': false , 'colors': 'blue' });
// => objects for 'fred' and 'mary'

2 个答案:

答案 0 :(得分:2)

是的,只需在回调函数o.colors.indexOf(color)中添加一个条件  要检查数组中是否color,这将返回purple颜色为{1}}的非活动用户:

_.filter(users, (o) => { return !o.active && o.colors.indexOf('purple') > -1  });

Array.indexOf

Array.includes



let users = [
  { 'user': 'barney', 'age': 36, 'active': true, 'colors': ['blue', 'yellow'] },
  { 'user': 'fred',   'age': 40, 'active': false, 'colors': ['blue', 'purple'] },
  { 'user': 'mary',   'age': 40, 'active': false, 'colors': ['blue', 'grey'] }
];

_.filter(users, { 'colors': 'blue' });
// => all objects as they all contain 'blue'

// using Array.indexOf
let myUsers = _.filter(users, (o) => { return !o.active && o.colors.indexOf('purple') > -1  }); 

// using Array.includes ( ES6 )
let myUsers2 = _.filter(users, (o) => { return !o.active && o.colors.includes('purple') }); 

console.log('using IndexOf() : ', myUsers)
console.log('using includes() : ', myUsers2)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

在要筛选的颜色周围加上括号:{ 'colors': ['blue'] }

&#13;
&#13;
var users = [
  { 'user': 'barney', 'age': 36, 'active': true, 'colors': ['blue', 'yellow'] },
  { 'user': 'fred',   'age': 40, 'active': false, 'colors': ['blue', 'purple'] },
  { 'user': 'mary',   'age': 40, 'active': false, 'colors': ['grey', 'blue'] }
];

console.log(_.filter(users, { 'colors': ['blue'] }));
console.log(_.filter(users, { 'active': false, 'colors': ['blue'] }));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;
&#13;
&#13;