我想知道通过数组元素从集合中获取元素的最佳和最简单方法是什么?是否可以使用本机js?
以下是这种情况:
const ids = [1, 2, 3, 4]
const collection = [{id: 2}, {id: 234}, {id:1}, {id: 345}, {id: 3}, {id:4}, {id:323}];
预期输出应该如下:
[{id: 1}, {id: 2}, {id: 3}, {id: 4}]
是否已经内置了lodash?我知道我们可以使用filter和indexOf,但我想知道最短和最简单的方法是什么。
答案 0 :(得分:1)
简单JS
将filter
与includes
const ids = [1, 2, 3, 4]
const collection = [{id: 2}, {id: 234}, {id:1}, {id: 345}, {id: 3}, {id:4}, {id:323}];
const found = collection.filter(item => ids.includes(item.id));
console.log(found);

答案 1 :(得分:0)
使用lodash,您可以使用_.keyBy()
将collection
编入id
索引,然后使用_.at()
ids
获取项目:
const ids = [1, 2, 3, 4]
const collection = [{id: 2}, {id: 234}, {id:1}, {id: 345}, {id: 3}, {id:4}, {id:323}];
const result = _.at(_.keyBy(collection, 'id'), ids);
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;
答案 2 :(得分:0)
由于输出顺序必须与id
同步,因此请使用map
和find
var output = ids.map( s => collection.find( t => t.id == s ) )
<强>演示强>
var ids = [1, 2, 3, 4];
var collection = [{
id: 2
}, {
id: 234
}, {
id: 1
}, {
id: 345
}, {
id: 3
}, {
id: 4
}, {
id: 323
}];
var output = ids.map(s => collection.find(t => t.id == s));
console.log(output);
如果ids
中的某些值在collection
中没有等效值,则在filter
之后使用map
var output = ids.map(s => collection.find(t => t.id == s)).filter( s => !!s );
<强>演示强>
var ids = [1, 2, 3, 4, 5];
var collection = [{
id: 2
}, {
id: 234
}, {
id: 1
}, {
id: 345
}, {
id: 3
}, {
id: 4
}, {
id: 323
}];
var output = ids.map(s => collection.find(t => t.id == s)).filter( s => s );
console.log(output);