omygoodness
omygoodness

Reputation: 365

Ramda - how to add new property to objects in array

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

Upvotes: 2

Views: 1444

Answers (1)

Ori Drori
Ori Drori

Reputation: 191936

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>

Upvotes: 3

Related Questions