Lodash - 如何从集合中获取所有对象符合字符串条件数组

时间:2017-07-24 07:41:43

标签: javascript lodash

我正在尝试使用数组作为标准的集合中的对象

类似的东西:

let collection = [
{id: '1', text: 'Hello'}, 
{id: '2', text: 'Bye'},
{id: '3', text: 'See you'},
];

const criteria = ['1', '2'];

,结果必须是:

let newArray = [
{id: '1', text: 'Hello'}, 
{id: '2', text: 'Bye'}
];

有一种简单的方法可以用Lodash做到这一点吗?

2 个答案:

答案 0 :(得分:3)

你不需要lodash

let collection = [
{id: '1', text: 'Hello'}, 
{id: '2', text: 'Bye'},
{id: '3', text: 'See you'},
];

const criteria = ['1', '2'];

const filtered = collection.filter((obj) => {
 return criteria.indexOf(obj.id) >= 0;
});
console.log(filtered)

答案 1 :(得分:0)

如果您想使用Lodash,您可以执行以下操作,但正如上面的答案所述,在这种情况下没有必要!

let collection = [
{id: '1', text: 'Hello'}, 
{id: '2', text: 'Bye'},
{id: '3', text: 'See you'},
];

const criteria = ['1', '2'];

var result = _.filter(collection, function(item) {
        return _.indexOf(criteria, item.id) >= 0;
});