我想从Collections过滤掉两个obj,从服务器获取conditionArr,所以它是不可预测的。
我的代码是:
var users = [{
user: 'barney',
age: 36,
active: true
},
{
user: 'fred',
age: 40,
active: false
},
{
user: 'travis',
age: 37,
active: true
}
];
// the Array fetch from Server, so it's unpredictable.
var conditionArr = [{
user: 'barney'
}, {
user: 'fred'
}];
// _.filter
result = _.filter(users, conditionArr);
我的预期输出
// expect results:
[{
user: 'barney',
age: 36,
active: true
},
{
user: 'fred',
age: 40,
active: false
}
]
真实结果:
[]
THX。
----------- ----------分频器
我找到了一个更好的方法:
result = _.map(conditionArr, (con) => ({
...con,
...(_.find(users, { user: con.user })),
}))
... THX
答案 0 :(得分:2)
只需使用array.filter:
var users = [
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true}
];
var result = users.filter(({user}) => user === 'barney' || user === "fred");
console.log(result);
答案 1 :(得分:2)
var users = [{"user":"barney","age":36,"active":true},{"user":"fred","age":40,"active":false},{"user":"travis","age":37,"active":true}];
var conditionArr = [{"user":"barney"},{"user":"fred"}];
var result = _.intersectionBy(users, conditionArr, 'user');
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;
答案 2 :(得分:0)
如果您必须使用lodash实现此目的,您可以采用与array.filter
_.filter(users, ({user}) => user === 'barney' || user === 'fred');
答案 3 :(得分:0)
与许多其他lodash函数一样,_. filil将函数作为第二个参数(将数组中的每个元素作为参数),如果函数返回true,则该元素保留在结果中。
var users = [
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true }
];
// the Array fetch from Server, so it's unpredictable.
var conditionArr = [
{ user: 'barney'},
{ user: 'fred'}
];
// Simplified condition a bit. cond = ['barney', 'fred'];
var cond = _.map(conditionArr, cond => cond.user);
// _.filter
var result = _.filter(users, user => _.indexOf(cond, user.user) !== -1);
console.log('result', result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
答案 4 :(得分:-1)
在_.filter方法中,您需要传递如下示例
的功能_.filter(users, function(o) { return !o.active; });
var users = [{
user: 'barney',
age: 36,
active: true
},
{
user: 'fred',
age: 40,
active: false
},
{
user: 'travis',
age: 37,
active: true
}
];
// _.filter
var result = _.filter(users, function(obj) { return obj.user=='barney'||obj.user=='fred' });
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
答案 5 :(得分:-2)
use native js like -
let userSubset = users.map(function(obj, index) {
if (obj.user === "barney" || obj.user === "fred") return obj;
}).filter(Boolean);
console.log(userSubset);
// {user: "barney", age: 36, active: true}
// {user: "fred", age: 40, active: false}