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

时间:2019-03-31 19:06:32

标签: javascript 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

3 个答案:

答案 0 :(得分:5)

一种可能性是像这样将evolvemappath)组合在一起:

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>

答案 1 :(得分:2)

也可以只使用纯JavaScript es6:

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

答案 2 :(得分:0)

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

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