我喜欢jessegavin 的回答,但我使用lodash-deep对其进行了扩展以进行深度属性匹配。
var posts = [{ term: { name: 'A', process: '123A' } },
{ term: { name: 'B', process: '123B' } },
{ term: { name: 'C', process: '123C' } }];
var result = _.filterByValues(posts, 'term.process', ['123A', '123C']);
// results in objects A and C to be returned
jsFiddle
_.mixin({
'filterByValues': function(collection, key, values) {
return _.filter(collection, function(o) {
return _.contains(values, resolveKey(o, key));
});
}
});
function resolveKey(obj, key) {
return (typeof key == 'function') ? key(obj) : _.deepGet(obj, key);
}
如果您不信任 lodash-deep 或者您希望支持名称中带有点的属性,那么这里有一个更具防御性和健壮性的版本:
function resolveKey(obj, key) {
if (obj == null || key == null) {
return undefined;
}
var resolved = undefined;
if (typeof key == 'function') {
resolved = key(obj);
} else if (typeof key == 'string' ) {
resolved = obj[key];
if (resolved == null && key.indexOf(".") != -1) {
resolved = _.deepGet(obj, key);
}
}
return resolved;
}