[英]Ramda find two different nested key values
我是Ramda的新手,是否可能在同一对象级别中获得两个不同的键值?
我在下面添加了相同的代码:
在这里,列表对象具有用户和员工关键字,我尝试实现同时获取用户和员工详细信息。
const R = require('ramda');
var list = [
{"doc":{"Title":"test1","Relations":{"users":[{"name": "user1"}]}}},
{"doc":{"Title":"test2","Relations":{"employee":[{"name": "user2"}]}}}
];
var getDetails= R.map(
R.pipe(
R.prop('doc'),
R.pipe(R.path(['Relations', 'users']))
)
)
getDetails(list);
在我的代码中,我仅使用用户密钥。 可能同时获得密钥(用户和雇员)。
电流输出:
[[{"name": "user1"}], undefined]
预期输出:
[[{"name": "user1"}], [{"name": "user2"}]]
您所拥有的解决方案离解决方案不太远。
其他可以帮助您解决问题的功能是:
R.pick
将对象转换为仅包含您提供的键(例如users
, employee
)。 R.values
- R.values
函数等效于Object.prototype.values
。 R.chain
这允许您映射列表,然后展平嵌套列表。 const list = [ {"doc":{"Title":"test1","Relations":{"users":[{"name": "user1"}]}}}, {"doc":{"Title":"test2","Relations":{"employee":[{"name": "user2"}]}}} ] const getDetails = R.chain(R.pipe( R.path(['doc', 'Relations']), R.pick(['users', 'employee']), R.values )) const result = getDetails(list) console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
您可以使用ifElse
和isNil
函数:
var getDetails= R.map(
R.pipe(
R.prop("doc"),
R.pipe(
R.ifElse(
R.pipe(R.path(["Relations", "users"]), R.isNil),
R.path(["Relations", "employee"]),
R.path(["Relations", "users"])
)
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.