如何使用 ramda.js 将对象数组转换为整数数组并从这些对象中提取值?

How to convert an array of objects in an array of integers extracting values from those objects using ramda.js?

我正在尝试使用 Ramda.js 将对象数组转换为整数数组,从这些对象中提取值。我只需要保留具有 uid 值的节点 participants,但是,我似乎没有正确执行此操作。

我想改造这个

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 with 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>

好吧,你可以在 Ramda 中做到这一点,但你可以简单地使用 VanillaJS™ 来获得一个快速、单行、无库的解决方案:

const obj = {
  participants: [
    {entity: {uid: 1}},
    {entity: {uid: 2}}
  ]
}
obj.participants = obj.participants.map(p => p.entity.uid);
console.log(obj);

也可以只使用纯 JavaScript es6:

const uidArray = listObjects.participants.map(({ entity: { uid } }) => uid);