繁体   English   中英

Ramda:通过与另一个数组中的每个项目进行比较,从数组中获取对象

[英]Ramda: get objects from array by comparing with each item in another array

我有一个像:

ids = [1,3,5];

和另一个数组如:

items: [
{id: 1, name: 'a'}, 
{id: 2, name: 'b'}, 
{id: 3, name: 'c'}, 
{id: 4, name: 'd'}, 
{id: 5, name: 'e'}, 
{id: 6, name: 'f'}
];

我想要的是另一个数组,如:

array = [{id: 1, name: 'a'}, {id: 3, name: 'c'}, {id: 5, name: 'e'}];

我无法理解它。 到目前为止,我尝试过:

console.log(R.filter(R.propEq('id', <donnow what shud be here>), items);
console.log( R.pick(ids)(items))

如果你还想和Ramda一起做:

 const ids = [1,3,5]; const items = [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ]; console.log( R.filter(R.compose(R.flip(R.contains)(ids), R.prop('id')), items) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> 

您可以使用.filter.indexOf 请注意,这些是用于阵列的ECMA5方法,并且在IE8中不起作用。

var ids = [1, 3, 5];
var items = [
  {id: 1, name: 'a'}, 
  {id: 2, name: 'b'}, 
  {id: 3, name: 'c'}, 
  {id: 4, name: 'd'}, 
  {id: 5, name: 'e'}, 
  {id: 6, name: 'f'}
];

var filtered = items.filter(function(obj) {
  return ids.indexOf(obj.id) > -1;
});
console.log(filtered); // [{id: 1, name: 'a'}, {id: 3, name: 'c'}, {id: 5, name: 'e'}];

或者可能是没有Ramda的一个班轮

items.filter(x=>ids.includes(x.id))

我建议使用哈希表来加快查找速度。

 var ids = [1, 3, 5], items = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ], filtered = items.filter(function(obj) { return this[obj.id]; }, ids.reduce(function (r, a) { r[a] = true; return r; }, Object.create(null))); document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>'); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM