首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ramdajs:用满足规范的内部数组定位项

ramdajs:用满足规范的内部数组定位项
EN

Stack Overflow用户
提问于 2017-03-18 09:24:20
回答 1查看 39关注 0票数 0

考虑到这样的结构:

代码语言:javascript
复制
[
  {
    documentType: { id: 4001 }
    correspondence: [ { id: 1000 }, { id: 1010 } ]
  },
  {
    documentType: { id: 102 }
    correspondence: [ { id: 1000 } ]
  },
  {
    documentType: { id: 101 }
    correspondence: [ { id: 1001 } ]
  }
]

我试图使用ramda来查找内部对应数组包含1000的数组的索引。

我试过这样做:

代码语言:javascript
复制
R.filter(R.where({ correspondence: R.any(R.where({ id: 1000 }))}))(data)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-18 10:47:01

首先,您需要稍微修改谓词函数,将内部R.where更改为R.propEq,以允许对常量值而不是函数进行比较:

代码语言:javascript
复制
const pred = R.where({ correspondence: R.any(R.propEq('id', 1000))})

然后,我有两个如何处理这个问题的例子,它们都使用R.addIndex来捕获索引:

一种是在测试每个元素时使用R.reduce构建一个列表:

代码语言:javascript
复制
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将索引嵌入到每个元素中:

代码语言:javascript
复制
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]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42872580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档