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

时间:2016-05-07 17:15:54

标签: javascript arrays ramda.js

我有一个像:

这样的数组
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))

4 个答案:

答案 0 :(得分:4)

您可以使用.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'}];

答案 1 :(得分:4)

如果您仍想以ramda方式进行

Ramda REPL

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'}
];

R.filter(R.compose(R.flip(R.contains)(ids), R.prop('id')), items)

答案 2 :(得分:3)

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

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

答案 3 :(得分:0)

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

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