2

I am trying to add a new property to each object in the array. My test array:

const array = [
  {
    "name": 'Test'
  },
  {
    "name": 'Test2'
  }
]

I tried to use R.assoc('selected', false, array); but it didn't work as expected. As a result, I would like to get:

const array = [
  {
    "name": 'Test',
    "selected": false
  },
  {
    "name": 'Test2',
    "selected: false
  }
]

Any help will be appreciated

1 Answer 1

3

R.assoc works by making a shallow clone of an object, and setting/updating a property. In this case, you need to handle an array of objects. Use R.map to iterate the array, and create a new array with transformed cloned objects by applying R.assoc:

const fn = R.map(R.assoc('selected', false));

const array = [{"name":"Test"},{"name":"Test2"}];

const result = fn(array);

console.log(result);
<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.

3 Comments

Simple mistake again. Thank you :)
It happens to all of us. You're welcome :)
If you're looking for how to create a new property based on values from other properties from the same object, see this answer from the same author stackoverflow.com/questions/63208320/…

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.