ramda中有什么功能,如何通过嵌套键值找到键?我找到了一种如何在数组中查找对象的方法,但这无济于事。我需要这样的东西:
const obj = {
addCompany: {
mutationId: '1'
},
addUser: {
mutationId: '2'
},
addCompany: {
mutationId: '3'
}
}
const findByMutationId = R.???
findByMutationId('2', obj) // returns addUser
最佳答案
find
与propEq
和keys
结合使用
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的Pointpoint版本
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>
关于javascript - Ramda:通过嵌套键值查找对象键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45820811/