1

I'm trying to convert an array of objects into an array of integers extracting values from those objects using Ramda.js. I need to keep just the node participants with the uid values, however, it seems that I'm not doing this correctly.

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

3 Answers 3

5

One possibility is to combine evolve with map(path) like this:

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>

While I'm sure that there is a lens-based solution, this version looks pretty straightforward.

Update

A lens-based solution is certainly possible. 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/[email protected]"></script><script>
const {over, lensProp, map, view, lensPath} = ramda  </script>

Sign up to request clarification or add additional context in comments.

Comments

2

Also could use just pure JavaScript es6:

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

Comments

0

Well, you can do it in Ramda, but you can simply use VanillaJS™ for that and have a fast, one-line, library-free solution:

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

3 Comments

Just so you know, someone looking for a Ramda solution probably is not interested in a technique that modifies the input. Of course this could easily be fixed up not to do that.
I don't really know the philosophy of Ramda, thanks for the input! I just went for the simplest solution that fitted the OP's requirements
to fit the Op's requirements you needed to use ramda... Mutating the input is non an option in fp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.