Ramda:通过嵌套键值查找对象键 [英] Ramda: find object key by nested key value

查看:90
本文介绍了Ramda:通过嵌套键值查找对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ramda中是否有任何函数,如何通过嵌套键值找到键?我找到了一种如何在数组中查找对象的方法,但这无济于事.我需要这样的东西:

Is there any function in ramda how can I find key by nested key value? I found a way how to find an object in array but that doesn't help. I need something like this:

const obj = {
  addCompany: {
    mutationId: '1'
  },
  addUser: {
    mutationId: '2'
  },
  addCompany: {
    mutationId: '3'
  }
}
const findByMutationId = R.???
findByMutationId('2', obj) // returns addUser

推荐答案

查找 propEq keys 结合使用应该有效

find combined with propEq and keys should work

const obj = {
  addCompany: {
    mutationId: '1'
  },
  addUser: {
    mutationId: '2'
  },
  addCompany2: {
    mutationId: '3'
  }
}
const findByMutationId = id => obj => R.find(
  R.o(R.propEq('mutationId', id), R.flip(R.prop)(obj)),
  R.keys(obj)
)

console.log(findByMutationId('2')(obj))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

无点版本( lulz )

const obj = {
  addUser: {
    mutationId: '2'
  },
  addCompany: {
    mutationId: '3'
  }
}

const findByMutationId = R.compose(
  R.o(R.head),
  R.o(R.__, R.toPairs),
  R.find,
  R.o(R.__, R.nth(1)),
  R.propEq('mutationId')
)

console.log(findByMutationId('2')(obj))

const findByMutationId2 = R.compose(
  R.ap(R.__, R.keys),
  R.o(R.find),
  R.o(R.__, R.flip(R.prop)),
  R.o,
  R.propEq('mutationId')
)

console.log(findByMutationId2('3')(obj))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

这篇关于Ramda:通过嵌套键值查找对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆