0
\$\begingroup\$

I'm mapping through an array of objects and applying conditions on each object by adding a new value according to the condition. I use map in ramda. Can I do this better?

events = map(el => {
  if (!['ts', 'sxi', 'ht', 'hd'].includes(el.value)) {
    el['extras'] = {type: 'cx', label: 'Es', name: 'es', options: ['cf']}
  }
  return el;
}, events);
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

You can skip Ramda altogether. JS has a built-in array.map().

I'd avoid doing side-effects on a map operation. The goal of a map operation is to transform one array of things into another array of things without affecting the original array or its contents. Not following this breaks expectations, and thus your code's reliability.

If you intend to mutate, use array.forEach() instead. Otherwise, if you want to continue using array.map(), create new objects.

You can do either of the following:

// Not mutating elements of events
const newEvents = events.map(e => {
  if (!['ts', 'sxi', 'ht', 'hd'].includes(el.value)) {
    // Copy e to a new object, append extras to this new object.
    return { ...e, extras: {type: 'cx', label: 'Es', name: 'es', options: ['cf']} }
  } else {
    // Changed nothing, return original element.
    return e
  }
})

// Mutating elements of events
events.forEach(e => {
  if (['ts', 'sxi', 'ht', 'hd'].includes(el.value)) return
  e['extras'] = {type: 'cx', label: 'Es', name: 'es', options: ['cf']}
})
\$\endgroup\$
1
\$\begingroup\$

If you are not returning a new set of values from map just modifying the element, then you should just use each

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.