0

I have an array of object like this:

[
  {type: 'x', 'attributes': {status: 'emitted', num: 1}}, 
  {type: 'y', attributes: {status: 'changed', num: 2}}
]

I want to change every status: emitted to 'done' and every status: 'changed' to 'error'

How can I do this with ramda?

3 Answers 3

1

Create a Map of statuses and their replacements, and a function to return the replacement (updateStatus) when given a value (current). Iterate the array with R.map, and use R.evolve to create a new object with updated status.

const status = new Map([['emitted', 'done'], ['changed', 'error']])

// get the current state replacement from the Map or use current if no replacement is available
const updateStatus = current => status.get(current) || current

const fn = R.map(R.evolve({
  attributes: {
    status: updateStatus
  }
}))

const data = [{type: 'x', 'attributes': {status: 'emitted', num: 1}}, { type: 'y', attributes: {status: 'changed', num: 2}}]

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

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

Comments

0

To fully appreciate the API ramda provides, I think it's worth it to add the "plain" javascript alternative (If you're willing to use the ECMAScript 2018 Object Spread syntax).

In the function arguments, you destructure your object right up until the properties you'd like to modify. All others props are collected in a ...rest parameter.

In the body of the map function, you recreate a new object, making the modifications to the properties you need.

As you can see, it can be quite hard to parse out the parts that are being changed. +1 to the ramda approach 🙂

const entries = [ { type: 'x', 'attributes': {status: 'emitted', num: 1}}, { type: 'y', attributes: {status: 'changed', num: 2 } } ];

const statusMap = { "emitted": "done", "changed": "error" };

console.log(
  entries.map(
    ({ attributes: { status, ...ra }, ...re }) =>
    ({ attributes: { status: statusMap[status], ...ra }, ...re })
  )
);

Comments

0
import { lensPath, map, over } from 'ramda'

const status = {emitted: 'done', changed: 'error'}
const updateStatus = current => status[current] ?? current
const statusLens = lensPath(['attributes', 'status']) 
const updateStatus = map(over(statusLens, updateStatus))
updateStatus([
  {type: 'x', 'attributes': {status: 'emitted', num: 1}}, 
  {type: 'y', attributes: {status: 'changed', num: 2}}
])
// =>
// [
//   {type: 'x', 'attributes': {status: 'done', num: 1}}, 
//   {type: 'y', attributes: {status: 'error', num: 2}}
// ]

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.