0

I have an array for example

const array = [
  {
    "id": 1
  },
  {
    "id": 2
  }
]

I want to add a new property to that based on the value at the same index in array2 using Ramda.

const array2 = [
  {
    0: 'Test'
  },
  {
    1: 'Test2'
  }
]

I want the output to be:

const result = [
  {
    "id": 1,
    "name": 'Test'
  },
  {
    "id": 2,
    "name": 'Test2'
  }
]

I have got to something like this so far but not sure how I map the value.

const fn = R.map(R.assoc('name', value??));

const result = fn(array1);

1 Answer 1

2

You can make use of R.zipWith to combine the elements at each index together from two lists using a function to determine how they're combined.

This lets you make use of R.assoc as you had suggested to combine the two.

It will also make things simpler if you extract the value you are interested in out of the object from your array2 elements. Without assuming much beyond what you've shared here, you can make use of R.map wrapped with R.addIndex to provide the index when mapping over the array to extract the value associated with each index.

Combining all of this together:

const fn = (array, array2) => zipWith(
  assoc('name'),
  addIndex(map)((x, i) => x[i], array2),
  array,
)
Sign up to request clarification or add additional context in comments.

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.