我正在尝试将一个对象数组转换为一个整数数组,使用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/[email protected]"></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/[email protected]"></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);