按数组值从集合中获取项目

时间:2018-04-02 08:19:33

标签: javascript arrays collections filter lodash

我想知道通过数组元素从集合中获取元素的最佳和最简单方法是什么?是否可以使用本机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,但我想知道最短和最简单的方法是什么。

3 个答案:

答案 0 :(得分:1)

简单JS

filterincludes

组合使用



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;
&#13;
&#13;

答案 2 :(得分:0)

由于输出顺序必须与id同步,因此请使用mapfind

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);