根据Ramda

时间:2018-05-03 17:46:59

标签: javascript ramda.js

我有一系列独特的值:const array = [1, 2, 4]

我有一些unqiue对象: const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}]

使用Ramda如何从collection中包含类型的array中提取所有对象?

预期结果:[{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 4, eyes: 'blue'}]

3 个答案:

答案 0 :(得分:3)

使用R.innerJoin()



const array = [1, 2, 4]
const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}]

const joinByType = R.innerJoin(
  (o, type) => o.type === type
)

const result = joinByType(collection, array)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
&#13;
&#13;
&#13;

使用R.propEq()type属性与数组中的类型id进行比较,以更ramdaish方式使用相同的方法。我们需要使用R.flip()因为innerJoin在要比较的值之前传递对象。

&#13;
&#13;
const array = [1, 2, 4]
const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}]

const joinByType = R.innerJoin(R.flip(R.propEq('type')))

const result = joinByType(collection, array)

console.log(result)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

没有ramda

collection.filter(item => array.includes(item.type))

答案 2 :(得分:0)

我认为Mukesh Soni的答案就是你需要的。在Ramda中,它可能会显示filter(p => array.includes(p.type), collection),但这大致相同。

但Ramda完全是关于功能,并创建可重用且灵活的功能来满足您的需求。我至少会考虑写这样的东西:

const {curry, filter, contains, prop} = R

const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}]
const array = [1, 2, 4]

const filterBy = curry((propName, selectedValues, collection) => 
  filter(e => contains(prop(propName, e), selectedValues), collection))

const newCollection = filterBy('type', array, collection)

console.log(newCollection)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

我甚至可以更进一步,允许任意转换功能,而不仅仅是prop

const filterBy = curry((transform, selectedValues, collection) => 
  filter(e => selectedValues.includes(transform(e)), collection))

filterBy(prop('type'), array, collection)

但是,如果您希望在整个应用程序中使用它们,那么这些抽象通常只会有所帮助。如果这是您使用值列表来匹配的唯一位置,以便过滤集合,那么没有理由可以使用任何可重用的函数。

相关问题