考虑到这样的结构:
[
{
documentType: { id: 4001 }
correspondence: [ { id: 1000 }, { id: 1010 } ]
},
{
documentType: { id: 102 }
correspondence: [ { id: 1000 } ]
},
{
documentType: { id: 101 }
correspondence: [ { id: 1001 } ]
}
]我试图使用ramda来查找内部对应数组包含1000的数组的索引。
我试过这样做:
R.filter(R.where({ correspondence: R.any(R.where({ id: 1000 }))}))(data)发布于 2017-03-18 10:47:01
首先,您需要稍微修改谓词函数,将内部R.where更改为R.propEq,以允许对常量值而不是函数进行比较:
const pred = R.where({ correspondence: R.any(R.propEq('id', 1000))})然后,我有两个如何处理这个问题的例子,它们都使用R.addIndex来捕获索引:
一种是在测试每个元素时使用R.reduce构建一个列表:
const reduceWithIdx = R.addIndex(R.reduce)
const fn = reduceWithIdx((acc, x, i) => pred(x) ? R.append(i, acc) : acc, [])
fn(data) //=> [0, 1]第二种方法是在过滤前使用R.map将索引嵌入到每个元素中:
const mapWithIdx = R.addIndex(R.map)
const fn = R.pipe(
mapWithIdx(R.flip(R.assoc('idx'))),
R.filter(pred),
R.map(R.prop('idx'))
)
fn(data) //=> [0, 1]https://stackoverflow.com/questions/42872580
复制相似问题