[英]How to convert an array of objects in an array of integers extracting values from those objects using ramda.js?
我正在尝试将对象数组转换为使用Ramda.js从这些对象提取值的整数数组。 我只需要使用uid值保留节点参与者 ,但是,似乎我没有正确执行此操作。
我想改变这个
var listObejcts = {
"participants": [
{
"entity": {
"uid": 1
}
},
{
"entity": {
"uid": 2
}
}
]
}
对此:
{
"participants": [1, 2]
}
我已经尝试了上面的代码,但是没有用。 它仍在返回对象列表。
var transform = pipe(
over(lensProp('participants'), pipe(
filter(pipe(
over(lensProp('entity'), prop('uid'))
))
))
)
console.log(transform(listObejcts))
有人知道我怎么能做到吗?
可以在这里编辑代码-https: //repl.it/repls/PrimaryMushyBlogs
一种可能是将evolve
与map
( path
)结合在一起,如下所示:
const transform = evolve({participants: map(path(['entity', 'uid']))}) var listObjects = {participants: [{entity: {uid: 1}}, {entity: {uid: 2}}]} console.log(transform(listObjects))
<script src="https://bundle.run/ramda@0.26.1"></script><script> const {evolve, map, path} = ramda </script>
虽然我确定有一个基于镜头的解决方案,但此版本看起来非常简单。
基于lens
的解决方案当然是可能的。 这是一个这样的:
var transform = over( lensProp('participants'), map(view(lensPath(['entity', 'uid']))) ) var listObjects = {participants: [{entity: {uid: 1}}, {entity: {uid: 2}}]} console.log(transform(listObjects))
<script src="https://bundle.run/ramda@0.26.1"></script><script> const {over, lensProp, map, view, lensPath} = ramda </script>
也可以只使用纯JavaScript es6:
const uidArray = listObjects.participants.map(({ entity: { uid } }) => uid);
好的,您可以在Ramda中做到这一点,但是您可以简单地使用VanillaJS™并拥有一种快速,单行,无库的解决方案:
const obj = { participants: [ {entity: {uid: 1}}, {entity: {uid: 2}} ] } obj.participants = obj.participants.map(p => p.entity.uid); console.log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.