ramdajs:使用满足规范的内部数组定位项目
ramdajs: locating items with an inner array that satisfies a spec
给定这样的结构:
[
{
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]
给定这样的结构:
[
{
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]