简体   繁体   English

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

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

I'm trying to convert an array of objects into an array of integers extracting values from those objects using Ramda.js. 我正在尝试将对象数组转换为使用Ramda.js从这些对象提取值的整数数组。 I need to keep just the node participants with the uid values, however, it seems that I'm not doing this correctly. 我只需要使用uid值保留节点参与者 ,但是,似乎我没有正确执行此操作。

I'm want to transform this 我想改变这个

var listObejcts = {
  "participants": [
    {
      "entity": {
        "uid": 1
      }
    },
    {
      "entity": {
        "uid": 2
      }
    }
  ]
}

to this: 对此:

{
  "participants": [1, 2]
}

I've tried the code above but it didn't work. 我已经尝试了上面的代码,但是没有用。 It's still returning a list of objects. 它仍在返回对象列表。

var transform = pipe(
  over(lensProp('participants'), pipe(
    filter(pipe(
      over(lensProp('entity'), prop('uid'))
    ))
  ))
)

console.log(transform(listObejcts))

Does anybody know how I could achieve that? 有人知道我怎么能做到吗?

It's possible to edit the code here - https://repl.it/repls/PrimaryMushyBlogs 可以在这里编辑代码-https: //repl.it/repls/PrimaryMushyBlogs

One possibility is to combine evolve with map ( path ) like this: 一种可能是将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> 

While I'm sure that there is a lens-based solution, this version looks pretty straightforward. 虽然我确定有一个基于镜头的解决方案,但此版本看起来非常简单。

Update 更新资料

A lens -based solution is certainly possible. 基于lens的解决方案当然是可能的。 Here is one such: 这是一个这样的:

 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);

Well, you can do it in Ramda, but you can simply use VanillaJS™ for that and have a fast, one-line, library-free solution: 好的,您可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM