Javascript ramdajs:使用满足规范的内部数组查找项目
考虑到这样的结构:Javascript ramdajs:使用满足规范的内部数组查找项目,javascript,ramda.js,Javascript,Ramda.js,考虑到这样的结构: [ { documentType: { id: 4001 } correspondence: [ { id: 1000 }, { id: 1010 } ] }, { documentType: { id: 102 } correspondence: [ { id: 1000 } ] }, { documentType: { id: 101 } correspondence: [ { id: 1001 } ]
[
{
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)
首先,您需要稍微调整谓词函数,将内部
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]
首先,您需要稍微调整谓词函数,将内部
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]