0

I am trying to extract array of nodes from multiple objects using ramda.

Sample data:

const testData = {
  "117590": {
    "id": 117590,
    "nodes": [
      117864,
      117865,
      117866
    ]
  },
  "117591": {
    "id": 117591,
    "nodes": [
      117867,
      117868
    ]
  }
}

I tried to use such query: R.pluck('nodes', testData); But as a result I got:

{"117590": [117864, 117865, 117866], "117591": [117867, 117868]}

How to combine all nodes in one array? Here is my Ramda editor link

2 Answers 2

3

Option 1: Convert to array using R.values, and then pluck and flatten results.

Option 2: Use R.values, and then get the nodes and flatten using R.chain with R.prop.

const { pipe, values, pluck, flatten, chain, prop } = R

const fn1 = pipe(values, pluck('nodes'), flatten)
const fn2 = pipe(values, chain(prop('nodes')))

const testData = {"117590":{"id":117590,"nodes":[117864,117865,117866]},"117591":{"id":117591,"nodes":[117867,117868]}}

console.log(fn1(testData))

console.log(fn2(testData))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

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

2 Comments

Thank you. Both solutions are working but could you tell me which one is more efficient? I would like to use it with large set of objects.
The 2nd one should be more efficient (less loops). I haven't profiled but it usually doesn't really matter unless you have more than 20k objects.
1

Just think about it in two steps. First get the values of the object, and then take their node properties. The simplest way to get those nodes is to use chain (prop ('node')). The two steps can be combined with pipe or compose.

const getNodes = pipe (values, chain(prop('nodes')))

const testData = {117590: {id: 117590, nodes: [117864, 117865, 117866]}, 117591: {id: 117591, nodes: [117867, 117868]}}

console .log (getNodes (testData))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script> const {pipe, values, chain, prop} = R                                 </script>

Comments

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.